先定义一个state对象
state = {
members: [
{
name: 'ronffy',
age: 30
}
]
}
- 优化setState方法
this.state.members[0].age++; //错误示例
setState的第1种实现方法
const { members } = this.state;
this.setState({
members: [
{
...members[0],
age: members[0].age + 1,
},
...members.slice(1),
]
})
setState的第2种实现方法
this.setState(state => {
const { members } = state;
return {
members: [
{
...members[0],
age: members[0].age + 1,
},
...members.slice(1)
]
}
})
下面用用immer更新state
import produce from "immer";
//代码量更少,也较清晰
this.setState(produce(draft => {
draft.members[0].age++;
}))
2.优化reducer
immer的produce的拓展用法
普通reducer
const reducer = (state, action) => {
const { members } = state;
return {
...state,
members: [
{
...members[0],
age: members[0].age + 1,
},
...members.slice(1),
]
}
}
集合immer,reducer的写法
const reducer = (state, action) => produce(state, draft => {
draft.members[0].age++;
})
可以看到,通过 produce ,我们的代码量已经精简了很多;
不过仔细观察不难发现,利用 produce 能够先制造出 producer 的特点,代码还能更优雅:
const reducer = produce((draft, action) => {
draft.members[0].age++;
})
网友评论