[英]React, Redux, mapStateToProps and no rerendering despite state changes
[英]Redux State changes but component not rerendering
我的问题是我的initialState.userWeight
state 正在更新(我可以在 redux 开发工具中看到它)但我的组件没有更新,它没有把我的数组的最后一个值放在这里:user reduce 我的初始值。
case 'NEWWEIGHT':
const weight = action.payload.weight
const date = action.payload.date
state.userWeight = [...state.userWeight, {weight: weight, date: date}]
return {...state}
这是我的初始状态:
const initialState = {
userName: '',
userSize: 0,
userWeight: [],
userDate: '',
}
这是我的组件的样子:
const userWeightRedux = useSelector(state => state.userInfo.userWeight[Array.length - 1].weight)
console.log(userWeightRedux)
...
<Text style={styles.user}>{userWeightRedux}</Text>
所以console.log(userWeightRedux)
改变。 我是新来的反应,redux 并且不完全理解传播语法,也许问题就在这里,但没有找到任何东西,希望你能帮助我:)。
Array.length
是 Arrays 的原型属性。 你不能那样使用它。 默认情况下始终为 1。因此,您始终检索state.userInfo.userWeight
的第一个元素。 改用:
const userWeightRedux = useSelector(state => state.userInfo.userWeight[state.userInfo.userWeight.length - 1].weight)
或更温和的语法:
const userWeightRedux = useSelector(state => state.userInfo.userWeight.slice(-1)[0].weight)
尽管其他答案可以更好地解决您的特定问题...
你正在改变你的 state。 尽管您要退回新的 state object,但您会将旧的 state 弄得一团糟。 这将导致微妙的问题。 不要在减速器中改变任何东西。 所以...
// this line mutates the "outgoing" state
state.userWeight = [...state.userWeight, {weight: weight, date: date}]
return {...state}
应改写为:
return {...state, userWeight: [...state.userWeight, {weight: weight, date: date}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.