组件状态在开发工具中更新,但之后我调用this.state时没有

时间:2017-12-12 01:38:28

标签: reactjs material-ui

我有一个组件,我使用material-ui受控表示例作为数据表,使当前所选行的索引保持状态。这工作正常,我可以在react开发工具中看到状态正确更新。但是,当调用updatePick时,this.state.selected不会返回更新的值。

# this result will again contain a variable 'result'
* def result = call creator
* def return = result.result
* print return

React Dev工具显示我的状态 选中:[1]

我一直在研究,所以这里有一些我可以排除的事情。

  1. 将此绑定到函数没有帮助。我的理解是使用箭头函数否定了这一点的必要性。
  2. 我知道setState并不是同步发生的。 updatePick方法之后不会被触发,但必须单独切换,因此状态有足够的时间进行更新。
  3. 这是我的渲染功能

    constructor(props) {
        super(props);
        this.state = {
          selected: [],
        }
      }
    
      isSelected = (index) => {
        return this.state.selected.indexOf(index) !== -1;
      }
    
      handleRowSelection = (selectedRows) => {
        this.setState({
          selected: selectedRows,
        })
      }
    
    
      updatePick = () => {
        console.log(this.state.selected);  //Shows []
        console.log(this.state.selected[0]);  //undefined
        this.props.updateTodaysPick(this.props.players[this.state.selected[0]]);
      }
    

    这是我关于stackoverflow的第一个问题 - 希望它可以用到鼻烟。

    编辑:这是一个material-ui表设置,当表组件失去焦点(单击提交按钮)时取消选择该行。您可以在表的支柱中设置它。

1 个答案:

答案 0 :(得分:0)

您的问题是由于Material UI Table的默认行为造成的。

每次Table<RaisedButton/>时,clickedblurring

因此,在未选择任何行的情况下调用this.handleRowSelection(),从而清除this.state.selection

要阻止Table blurring onMouseDown使用onClick而不是this.updatePick()来致电<div className="submit"><RaisedButton label="Update Player" secondary={true} onMouseDown={this.updatePick} /></div>

preventDefault()

请务必在event参数上触发blur以阻止// Update Pick. updatePick = (event) => { // Prevent Table from blurring. event.preventDefault() // Update Todays Pick. this.props.updateTodaysPick(this.props.players[this.state.selected[0]]) }

{{1}}