I have an indexed list of users
in the JS object (not array). It's part of the React state.
{
1: { id: 1, name: "John" }
2: { id: 2, name: "Jim" }
3: { id: 3, name: "James" }
}
What's the best practice to:
Without any immutable helpers. I'm using Coffeescript and Underscore (so _.extend is ok...).
Thanks.
答案 0 :(得分:9)
This is what i would do
var newUsers = _.extend({}, users, { 4: { id: 4, ... } })
var newUsers = _.extend({}, users)
then delete newUsers['2']
var newUsers = _.extend({}, users)
then newUsers['2'].name = 'Peter'
答案 1 :(得分:5)
If you're not using Flux, you use this.setState() to update the state object.
delUser(id) {
const users = this.state.users;
delete users[id];
this.setState(users);
}
addChangeUser(id, name) {
const users = this.state.users;
users[id] = {id: id, name: name};
this.setState(users);
}
Then you can execute your test cases with this:
addChangeUser(4, 'Jane);
addChangeUser(2, 'Peter');
delUser(2);
答案 2 :(得分:2)
除_.extend外,您可以使用Map存储user
let user = new Map();
user.set(4, { id: 4, name: "Jane" }); //adds with id (4) as key
user.myMap.set(2, { id: 2, name: "Peter" }); // set user #2 to "Peter"
user.delete(3); //deletes user with id 3
答案 3 :(得分:0)
setState
也接受一个函数,您可能会发现它更直观
function add( user ) {
this.setState( users => {
users[ user.id ] = user
return users
}
}
function remove( id ) {
this.setState( users => {
delete users[ id ]
return users
}
这些函数假设您的state
对象 是您的users
对象,如果它实际上是state.users
那么您必须选择users
} out,将函数传递给setState
将始终通过实际的state
对象进行调用。
在此示例中,add
也可用于修改,具体取决于您的实际用例,您可能需要创建单独的帮助程序。
答案 4 :(得分:0)
使用点差:
添加
this.setState({
...this.state,
4: { id: 4, name: "Jane" },
}
删除ID 2
let prevState = this.state;
let {"2": id, ...nextState} = prevState;
this.setState({
...nextState,
}
更改ID 2
this.setState({
...this.state,
2: {
...this.state["2"],
name: "Peter",
}
}