【问题标题】:Redux state not updating with javascript objectRedux 状态未使用 javascript 对象更新
【发布时间】:2017-09-09 04:27:01
【问题描述】:

我有这个容器和组件以及我试图放入我的商店的对象yeast。但是,每当我尝试保存它时它都不起作用。对象看起来像这样

{ yeastType : value, temp: value}

Container.js

const mapDispatchToProps = (dispatch) => {
    return {
        handleYeastChange: (yeast) => {
            dispatch(actions.updateYeast(yeast))
        }
    }
};

const RecipeYeastContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(RecipeYeast);

Component.js

updateYeastState = (updatedYeast) => {
    this.props.handleYeastChange(updatedYeast)
};

我在控制台或任何东西中都没有错误。当我打开我的 redux 开发工具时,它告诉我在调用操作时状态已经更新。因此只保存输入到我的字段中的第一个字母。它永远不会坚持下去。它真的很奇怪。它也从未出现在 UI 中。我可以随心所欲地输入,并查看触发的动作和保持第一个字母但未显示在输入中的状态。

奇怪的是,当我更改代码以将 yeastTypetemp 都传递给属性函数并在其中构造对象时,它可以工作。 (见下文)

这可行:Container.js

const mapDispatchToProps = (dispatch) => {
    return {
        handleYeastChange: (yeastType, temp) => {
            const yeast = {yeastType, temp}
            dispatch(actions.updateYeast(yeast))
        }
    }
};

Component.js

updateYeastState = (updatedYeast) => {
    this.props.handleYeastChange(updatedYeast.yeastType, updatedYeast.temp)
};

我无法弄清楚为什么会这样。我以为我可以一直传递对象而不必重建它。

【问题讨论】:

  • 你应该在redux中调试和比较prev和next对象。当新对象更改时,只会更新状态。要调试,请继续按 F10,您将进入 redux 比较两个对象的地方。
  • @Ajaykumar 我试过了。每次击键都会更新状态,但只保留一个字母。 UI 永远不会更新,当我在 chrome 中检查时,组件上的道具永远不会更新,因此输入的值永远不会更新。然后每次击键都会覆盖状态中的最后一个字母,因为 UI 认为就是这样。似乎只要我在减速器路径的某处重建 yeast 对象,它就会保存,但我不能从组件一路传递它

标签: javascript reactjs redux react-redux


【解决方案1】:

您的action 发送正确吗?在使用redux 时,您不会更新组件的状态,而是更新store,然后组件中的值来自mapStateToProps 函数,该函数来自store。假设您正在使用名为 yourReducer 存储的对象更新您的 store。例如:

Container.js:

const mapStateToProps = (state) => ({
  inputValue: state.yourReducer.value
})
const mapDispatchToProps = (dispatch) => ({
  inputHandler: (e) => {
    dispatch(yourAction({type: 'CHANGE_INPUT', value: e.target.value}))
    // The store catches the action and pass to the reducer that can read the action's type
    // in `yourReducer` will catch the 'CHANGE_INPUT' type and
    // return a new value as same as the value that passed from the action
  }
})
export default connect(mapStateToProps)(Component)

组件.js

export default class Component extends React.Component {
  { your custom function here ... }

  render() {
    const { inputValue, inputHandler } = this.props
    return (
      <div>
        {/* The input will be the same as the inputValue changed */}
        <input value={inputValue} onChange={inputHandler} />
      </div>
    )
  }
}

要调试redux,您可以试试这个redux-devtool

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多