我有一个有几个用户的应用程序。我现在想能够创建一个新用户。所以我创造了这个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