2017-05-27 13 views
-1

我正在尝试使文本框自动对焦。setState被调用太迟

但是,我看来setState被称为太晚了。

它被称为Popup.show。我为console.log创建了一个按钮状态,它似乎设置为true,但它一定发生得太晚。

我怎样才能得到setState作为Popup.show发生?

class Dashboard extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     focused: false, 
    }; 
    } 
    onClick = (event) => { 
    console.log('Says focussed FALSE', this.state.focused) 
    this.setState({ focused:true }); 
    Popup.show(<div> 
     <SearchBar 
     autoFocus 
     focused={this.state.focused} 
     /> 
     <button onClick={this.checkState}>It says TRUE here</button> 
    </div>, 
    console.log('Says focussed FALSE still', this.state.focused), 
    { animationType: 'slide-up'}); 
    }; 
    checkState = (e) =>{ 
    console.log(this.state) 
    } 
    render() { 
    return (
     <div style={{ padding: '0.15rem' }}> 
     <Button onClick={this.onClick.bind(this)}>Open & Focus</Button> 
    </div>); 
    } 
} 
+1

[为什么调用setState方法不立即改变状态?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately ) –

回答

2

永远记住,setState不会立即执行。如果您setState后要Popup.show(),你可以使用一个回调:

this.setState({ focused: true },() => { 
    Popup.show(...) 
}) 

而且你已经在使用箭头功能,你不需要在渲染功能.bind(this)

+0

这似乎已经奏效 - 但它并不是仍然在聚焦。有另一种方法可以做到这一点我可以测试吗? – Ycon

+0

这可能与'Popup'和'SearchBar'有关 – CodinCat

0

setState不立即集中的状态

来自:的setState()的https://facebook.github.io/react/docs/react-component.html#setstate

想作为一个请求而不是立即命令更新组件。为了获得更好的感知性能,React可能会延迟它,然后一次更新几个组件。 React不保证立即应用状态更改。

改变你setState到像

this.setState({ focused: true },() => { 
    Popup.show(<div> 
    <SearchBar 
    autoFocus 
    focused={this.state.focused} 
    /> 
    <button onClick={this.checkState}>It says TRUE here</button> 
    </div>) 
}); 
+0

我认为这已经奏效,我的'focused = {this.state.focused}'仍然没有反应。这有可能是什么原因? – Ycon

+0

如果您将其更改为:'this.setState({focused:true},()=> console.log(this.state.focused));'是否在控制台中表示为真?如果是这样,问题可能在于您的搜索栏 – user2340824