React组件未使用当前状态更新,但mapStateToProps正在更新

时间:2017-04-16 00:24:29

标签: reactjs redux

我是React的新手,我正在尝试根据Todo示例构建一个Redux商店。我可以添加Todo项和状态更新,但由于某种原因,组件不会更新。

   // This works and the console.log matches the current state.
    const mapStateToProps = (state) => {
      console.log('map state to props', state);
      return {
        todos: getVisibleTodos(state.todos, state.visibilityFilter)
      }
    }

但是组件道具不会更新,todo只是一个空白对象{};我在这里简化了组件代码:

    class TestTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      todos: props.todos
    };

    // Shows 0 todo's
    console.log('constructor props', props.todos)

    setTimeout(function() {
      // Still 0 todo's even though mapStateToProps & the UI shows 10.
      console.log('constructor props', props.todos);
    }, 2000)

    /* DEMO */
    this._addTodo = this._addTodo.bind(this);
    /* */
  }

  // Add fake to do item.
  _addTodo(index) {
    this.props.dispatch(
      addTodo(
        'test: ' + index,
        'test lastName: ' + index,
        'test dob: ' + index,
        '999-999-9999',
        'testing@test' + index + '.com',
        'Test - ' + index
      )
    )
  }

  componentDidMount() {
    // Add 10 todo items.
    for(let i = 0; i < 10; i += 1) {
      this._addTodo(i);
    }
  }

  render() {
    return (
      <div>
        <Table
          ...
        </Table>
      </div>
    );
  }
}

TestTable = connect(mapStateToProps)(TestTable)

export default TestTable

3 个答案:

答案 0 :(得分:0)

将此添加到组件似乎可以解决问题,但不确定这是否是最佳做法。

  componentWillReceiveProps(props) {
    console.log('component will receive props', props);
    console.log('props todos: ', props.todos);
    this.setState({
      todos: props.todos
    })
  }

答案 1 :(得分:0)

 componentWillReceiveProps(props) {
    console.log('component will receive props', props);
    console.log('props todos: ', props.todos);
    this.setState({
      todos: props.todos
    })
  }

这段代码非常糟糕,因为你卡它会创建一个无限循环。每次进行setState时,它都会重新渲染组件并调用函数componentWillReceiveProps。哪个setState将重新呈现.... 为了防止循环,我通常在setState周围添加一个if来在你到达你想要的东西时停止循环

无法对您之前的回答发表评论,所以我在这里写这篇文章

答案 2 :(得分:0)

您可以使用react.16生命周期方法设置状态或观看道具更改:

第一个方法应返回新的状态对象。

第二种方法将在组件属性或状态更改时执行。 componentDidUpdate

KeyListener

相关问题