我已经用Google搜索,但没有任何帮助。 我知道在redux中返回相同对象时,react Component不会重新渲染。不管我没有改变商店,我都在使用来自'react-redux'和其他组件的连接
谢谢:D
//I'm updating a attribute value from this object:
{name: 'some name', score: 0,}
//to
{name: 'some name', score: 1,}
//just change the score
//Component:
class ListTeam extends Component {
render() {
return (
<ListContainer onNewTeam={this.props.onNewTeam}>
{this.props.listTeam.map((item) =>
<Item
name={item.name}
score={item.score}
key={item.toString()}
/>
)}
</ListContainer>
)
}
}
const mapToProps = (store, props) => {
return {
listTeam: store.listTeam
}
}
export default connect(mapToProps)(ListTeam)
减速机:
case 'ADD_POINT':{
let newstate = Object.assign({},state); //new state from current state
let current = newstate.currentPlayer //get current player
let listTeam = newstate.listTeam; //getListTeam
listTeam[current].score++; //+1 to score
return {
...state,
listTeam
}
}
答案 0 :(得分:1)
您错过的是在connect
提供的react-redux
中,它只会浅比较当前状态和先前状态。由于您仅将currentPlayer
和listTeam
从存储传递到组件,因此在执行操作ADD_POINT
之后,将保留对象listTeam
并保持其所有键不变,{{1} }逻辑确定不应进行任何更新。这是a small example in redux's github个发布线程,与您的实现无关。
一个简单的解决方案是每次更新时在商店中克隆connect
,以便将其识别为新对象:
listTeam
我用于上述解决方案的简单Codesandbox:https://codesandbox.io/s/xjp77jpyro
您还可以按照Redux的建议使用Immutable处理不可变状态。
另一种解决方案是自定义 case 'ADD_POINT':{
let newstate = Object.assign({},state); //new state from current state
let current = newstate.currentPlayer //get current player
let listTeam = newstate.listTeam; //getListTeam
listTeam[current].score++; //+1 to score
return {
...state,
listTeam: JSON.parse(JSON.stringify(listTeam)
}
}
函数以强制其识别connect
:https://react-redux.js.org/api/connect#options-object中的更改。但我认为您不需要走那么远。