【问题标题】:Component with local state not updating on React Redux具有本地状态的组件未在 React Redux 上更新
【发布时间】:2017-04-02 08:16:30
【问题描述】:

我正在尝试创建一个独立组件MultiSelect(我知道那里有组件,但我想学习如何做)。

我以一种将所选值存储在其状态中的方式创建它。

我从我的容器中这样称呼它:

<MultiSelect
  items={ this.props.boards }
  label="Boards"
  value={ this.props.selectedBoards }
  onChange={ e => this.onChange(e) } />

当我调度一个动作时,我会得到容器道具的正确值。我的 MultiSelect 甚至显示正确的选项。但是由于某种原因,它不会更新选定的值。在容器中this.props.selectedBoards 有正确的值,但是组件没有得到这个更新。

export default class MultiSelect extends React.Component {
  constructor(props) {
    super(props); // props.items = all options to select

    this.state = {
      selectedItems: props.value || [], // selected options (problem)
      search: '',
      hidden: true,
    };
  }

  render() {
    return (<div>
      ...
      this.state.selectedItems

要选择的选项在props(有效)上,所选选项在state(不会更新)上。

如何使用处于状态的selectedItems 的新值更新MultiSelect 组件?或者推荐的创建这样的组件的方法是什么?

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

    我最终将selectedItems 从state 移动到props,然后在选择元素的onChange 事件中,我从props 获取值,添加/删除更改的item 并使用修改后的数组调用 this.props.onChange。

    然后在容器上,我使用新数组调度一个动作,以便获得一个新状态。

    我通过将跟踪所选项目的任务委托给容器来解决它。

    多选:

    export default class MultiSelect extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          search: '',
          hidden: true,
        };
      }
    
      onChange(item) {
        const selectedItems = [ ...this.props.selectedItems ];
    
        const index = selectedItems.findIndex(element => element.value === item.value);
    
        if (index !== -1) {
          selectedItems.splice(index, 1);
        }
        else {
          selectedItems.push(item);
        }
    
        this.props.onChange(selectedItems); // container
      }
    
      render() {
        return (<div>
          ...
          this.props.selectedItems
    

    容器:

    onChange(data) {
      this.props.dispatch({ type: 'SetSelectedBoards', data });
    }
    
    <MultiSelect
      items={ this.props.boards }
      label="Boards"
      selectedItems={ this.props.selectedBoards }
      onChange={ e => this.onChange(e) } />
    

    【讨论】:

    • 这是一个很好的解决方案,但是如果您想在将来对 prop 更改做出反应,请查看 componentWillReceiveProps 方法。
    猜你喜欢
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2018-09-25
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多