图中默认红色区域是根据hostedLand
这个数组来渲染的,初始length为1。
点击添加按钮后hostedLand
的length为2
添加按钮是没有问题的,可是我点击删除后全局state
中的hostedLand
的length会变小。但是渲染出来的是这样
并且控制台也不输出任何东西。
reducer:
const hostedLand = (state = [initState], action) => {
switch(action.type) {
// 增加
case 'ADD_HOSTEDLAND':
return [
...state,
{...initState,
id: action.id
}
]
// 删除
case 'DELETE_LAND':
state.splice(action.id, 1)
return state
.....
}
}
组件相关代码:
import { addHostedLand } from '../actions'
const mapStateToProps = state = {
// 省略
}
const mapDispatchToProps = dispatch => {
return {
addHostedLand: () => dispatch(addHostedLand()),
deleteLand: (...args) => dispatch(deleteLand(...args)),
}
}
class HomeComponent extends Component {
render(){
const { hostedLand, addHostedLand } = this.props
console.log(hostedLand)
return (
<div>
{hostedLand.map(land =>
<OtherComponent {...this.props} key={land.id} id={land.id} />
)}
<button onClick={addHostedLand}>添加</button>
<div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomeComponent)
OtherCompoent:
...
render () {
const {id, deleteLand } = this.props
return () {
.....
<button onClick={() => deleteLand(id)}>删除<button>
.....
}
}
...
在 reducer 中,删除的时候返回的是原数组,hostedLand 对象没有更新,仍为原对象,不会触发 re-render;增加的时候返回的是新数组,hostedLand 对象发生了改变,所以会触发 re-render。