2017-09-24 87 views
0

我想设置状态,然后在设置它之后调用当前状态的另一个函数。this.setState不工作

我有这样的代码

this.setState({ 
     candidates : diCandi 
    },()=>{ 
     this.createDataSource(this.state) 
     console.log("The state is=>",this.state); 
    }); 

我想打电话给this.createDataSource(this.state)与我刚刚更新的状态。 它不工作我不知道为什么。有什么我做错了

Infact当我注销状态。我从来没有看到日志中的代码。

+1

_not working_是不够的信息。请给你的问题更多的背景。如果您收到任何错误或奇怪的行为,请将其添加到您的问题。 – bennygenel

+1

这应该工作,回调的关键是它不会触发,直到状态更新(因为这可能是异步)。请使用Stack Snippets('[<>]'工具栏按钮)使用** runnable ** [mcve]更新您的问题。 Stack Snippets支持React,包括JSX; [这是如何做一个](http://meta.stackoverflow.com/questions/338537/)。 –

+0

澄清什么是“不能工作”。你可以尝试在'createDataSource'内登录,看看状态是否是新的(它应该是)。所以你需要找出什么是不工作的。 – Panther

回答

1

class App extends React.Component{ 
 
    constructor(props){ 
 
    super(props) 
 
    this.state = { candidates: "no candidates" } 
 
    } 
 
    
 
    shouldComponentUpdate(){ 
 
    return false; 
 
    } 
 
    
 
    buttonClick(e){ 
 
    this.setState({candidates: "diCandi"},() => console.log("updated")) 
 
    } 
 
    
 
    render(){ 
 
    return(
 
    <div> 
 
     <button onClick={this.buttonClick.bind(this)}>set candidates</button> 
 
     <b>{this.state.candidates}</b> 
 

 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
const MOUNT_NODE = document.getElementById('container') 
 
ReactDOM.render(<App />, MOUNT_NODE)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container">

如早些时候萨格尔,在this.setState回调(中提到的代码应工作)只踢英寸回调的工程,即使shouldComponentUpdate是返回false

-2

试试这个:

this.setState({ 
    candidates : diCandi 
}).then(()=>{ 
    this.createDataSource(this.state) 
    console.log("The state is=>",this.state); 
}); 

this.setState()是一个异步函数。国家已经设置后

+0

谢谢,但为我工作 – henrybbosa

1

您发送所有状态createDataSource你可以做

this.setState({ 
    candidates : diCandi 
},()=>{ 
    this.createDataSource(this.state.candidates) 
    console.log("The state is=>",this.state.candidates); 
}); 

还建议从createDataSource方法访问状态不发送它作为PARAMS

this.setState({ 
    candidates : diCandi 
},()=>{ 
    this.createDataSource() 
    console.log("The state is=>",this.state.candidates); 
}); 
createDataSource

createDataSource() { 
    this.state.candidates 
    .... rest of code 
} 

然后