React Redux使用状态和状态更改重新获取数据

时间:2017-01-25 15:05:59

标签: reactjs react-redux

我想将数据从我的状态传递到提取调用(例如搜索字词)。当状态改变时,它应该重新获取我的数据。

生命周期方法似乎是这样做的地方,但是当我使用它时它或者什么都不做(渲染在状态改变之前被调用),或者它继续循环。

这是我的简化代码:

@connect((store) => {
    return {
        collections : store.collections.collections
    }
}, {
    fetchCollections
})
export default class CollectionPane extends Component {

    constructor(props){
        super(props);

        this.state = {
           term : null
        }
    }

    componentWillMount(){
        this.handleFetchCollections(this.state.term);   // This loads initial ok
    }

    componentDidUpdate(){
        // this.handleFetchCollections(this.state.term);  // This causes loop
    }

    handleFetchCollections(props, sort){
        log('Fetching...', 'green');
        this.props.fetchCollections(props, sort);
    }

    onSearch(){
		
		const term = "test example";
		
		this.setState({
			term
		})
    }

    render(){
        const { collections } = this.props;

        return (
            <div>
                <a style={{ display: "block", padding: "1em" }} onClick={this.onSearch.bind(this)}>Search</a>

                <CollectionList collections={collections} />
            </div>
        );
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>

2 个答案:

答案 0 :(得分:4)

在执行提取之前,您应该将新状态与之前的状态进行比较:

componentDidUpdate(prevProps, prevState) {
    if (prevState.term !== this.state.term) {
        this.handleFetchCollections(this.state.term);
    }
}

答案 1 :(得分:1)

使用react-redux,你应该通过动作和减少器改变你的状态。然后,您可以使用此处所述的异步操作:http://redux.js.org/docs/advanced/AsyncActions.html

相关问题