【问题标题】:Redux State changes but component not rerenderingRedux 状态更改但组件未重新渲染
【发布时间】:2022-01-07 09:57:04
【问题描述】:

我的问题是我的 redux 状态正在更新(我可以在 redux 开发工具中看到它)但我的组件没有更新,它没有放入数组的最后一个值 initialState.userWeight 这是我的减速器的样子:

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并且不完全理解传播语法,也许问题就在这里但没有找到任何东西,希望你能帮助我:)。

【问题讨论】:

    标签: javascript reactjs react-native redux react-redux


    【解决方案1】:

    Array.length 是数组的原型属性。你不能那样使用它。默认情况下始终为 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)
    

    【讨论】:

    • 有一点,但应该考虑在选择器中保护一个空数组。
    【解决方案2】:

    虽然其他答案可以更好地解决您的具体问题...

    你正在改变你的状态。尽管您正在返回一个新的状态对象,但您的旧状态却一团糟。这将导致微妙的问题。不要在减速器中改变任何东西。所以...

    // 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}]} 
    

    【讨论】:

    • 我认为这不是问题。它本质上将传入状态用作临时容器。我也不喜欢它的写法,但无论如何它都会被返回值取代。
    猜你喜欢
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多