我有一個有幾個用戶的應用程序。我現在想能夠創建一個新用戶。所以我創造了這個actionCreator:Object.assign不會更新我的狀態(React)
export const createUser = (first, last) => {
console.log("You are about to create user: XX ");
return {
type: 'USER_CREATE',
first: first,
last: last,
payload: null
}
};
我與第一&姓氏只處理現在。 actionCreator從容器中獲取參數。有它調用actionCreator像這樣一個按鈕:
<button onClick={() =>this.props.createUser(this.state.inputTextFirstName, this.state.inputTextLastName)}>Submit</button>
我UserReducer看起來是這樣的:
/*
* The users reducer will always return an array of users no matter what
* You need to return something, so if there are no users then just return an empty array
* */
export default function (state = null, action) {
if(state==null)
{
state = [
{
id: 1,
first: "Bucky",
last: "Roberts",
age: 71,
description: "Bucky is a React developer and YouTuber",
thumbnail: "http://i.imgur.com/7yUvePI.jpg"
},
{
id: 2,
first: "Joby",
last: "Wasilenko",
age: 27,
description: "Joby loves the Packers, cheese, and turtles.",
thumbnail: "http://i.imgur.com/52xRlm8.png"
},
{
id: 3,
first: "Madison",
last: "Williams",
age: 24,
description: "Madi likes her dog but it is really annoying.",
thumbnail: "http://i.imgur.com/4EMtxHB.png"
}
]
}
switch (action.type) {
case 'USER_DELETED':
return state.filter(user => user.id !== action.userIdToDelete);
case 'USER_CREATE':
console.log("Action first:" + action.first);
console.log("Action last:" + action.last);
Object.assign({}, state, {
id: 4,
first: action.first,
last: action.last,
age: 24,
description: "Some new Text",
thumbnail: "http://i.imgur.com/4EMtxHB.png"
});
return state;
}
return state;
}
現在我有幾個問題。 1)這是做到這一點的正確方法,還是我在某處編寫錯誤的代碼?請記住,我試圖在這裏使用Redux,但我不完全確定我是否有時不會回落到沒有Redux的React
2)我是否正確地執行狀態對話?我最初使用教程,我現在建立在這一點,但我不知道爲什麼狀態似乎是一個數組:
state = [ <--- Does this mean that my state is an array?
{
id: 1,
// and so on ...
我對這個很困惑,因爲在其他教程狀態只是包含其他的對象更小的對象,全部用圓括號{}
3)創建新用戶的最佳方式是什麼?我的Object.assign不起作用,它不更新任何內容,我不確定錯誤在哪裏。
4)而且,相關地,我如何更新一個個人用戶或一個個人用戶的財產?
關於Object.assign()您不會將Object.assign()的結果賦值給任何變量以在操作之後使用。 Object.assign()返回一個新對象:爲了合併而傳遞的對象保持不變。所以你的對象狀態和以前一樣。 – Flyer53