React Redux 使用状态和状态变化重新获取数据

React Redux re-fetch data using state and state change

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

生命周期方法似乎是执行此操作的地方,但当我使用它们时,它要么什么都不做(在状态更改之前调用渲染),要么进入无限循环。

这是我的简化代码:

@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>

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

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

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