如何在数据更新后重新渲染Reactjs组件?

时间:2015-10-19 18:48:16

标签: reactjs

这是我的组件的结构:

module.exports =  React.createClass({

    getInitialState(){
        data = .... //by connecting to a db server

        var properties = fun(...)   //other functions manipulating the data

        return {

            data:data,
            .... //other UI functions

        }

    onSearch(e){
            e.preventDefault();
            var startdate = React.findDOMNode(this.ref.start).value;

            //******** here I want to update the data in the view using this new startdate  
            //so essentially I just want to replace "data = " in the getInitialState() bcoz I
            //want other data manipulation functions from getInitialState to run as well.       
        }

    render(){

        return(
            <form className = "dateform" onSubmit = {this.onSearch}>
                <input type = "text" ref = "start" />
            </form>

            ...

            //other UI return stuff
        )
    }
)}

我应该怎么做// *******?

我想根据我在表单字段中的日期更新getInitialState()中的数据变量。然后用新数据刷新视图。我应该在onSearch函数中做出哪些更改?

这是一种正确的方法吗?

onSearch()
{
     data = //make $.ajax call to get new data
    this.setState({
        data: data
   });

}

1 个答案:

答案 0 :(得分:4)

查看州in documentation here。你可以通过调用setState方法来改变它:

onSearch (e) {
    // get somehow new data

    this.setState({
        data: newData
    });
}