2017-05-19 115 views
1

我目前正在使用react和redux构建我的第一个应用程序。我建立了一些过滤器,当用户选择一个过滤器时,它将用新的过滤器值更新商店,然后请求新的结果。React/Redux等待商店更新

存储正在使用新的过滤器值进行更新,但在存储更新完成之前发生获取请求,因此会返回不正确的值。

如何在提取请求之前等待商店更新?

下面是我的代码...

const mapStateToProps = (state) => { 
    return { 
     dataFilter: state.dataFilter 
    } 
}; 

class Filters extends Component { 
constructor(props){ 
    super(props); 
    this.handleChange = this.handleChange.bind(this); 
} 

handleChange(value, dispatcher){ 
    dispatcher(value.props["data-attr"]); 

    this.props.resultsFetchData('/api/deals/?data=' + this.props.dataFilter); 
} 

render() { 
    const dataFilters = { 
     0: <span data-attr="0">Any</span>, 
     20: <span data-attr="1">1GB+</span>, 
     40: <span data-attr="2">2GB+</span>, 
     60: <span data-attr="5">5GB+</span>, 
     80: <span data-attr="10">10GB+</span>, 
     100: <span data-attr="99.99">Unltd</span> 
    }; 

    return (
     <div className="filters"> 
      <div className="row"> 
       <div className="col-sm-4 filters--slider"> 
        <Slider 
         min={0} 
         marks={dataFilters} 
         step={null} 
         defaultValue={this.props.dataFilter} 
         onChange={e => {this.handleChange(dataFilters[e], this.props.setDataFilter)}} /> 
       </div> 
      </div> 
     </div> 
     ); 
    } 
} 

export default connect(mapStateToProps, {setDataFilter, resultsFetchData})(Filters) 

Filters.propTypes = { 
dataFilter: PropTypes.string 
} 
+0

可以在mapStateToProps添加一个检查:'dataFilter:状态&&状态。 dataFilter? state.dataFilter || anyDefaultValue'。或者在'handleChange()' 中,你可以添加一个if语句来检查prop是否有效。 –

+1

或者您可以将获取调用移动到componentWillReceiveProps方法中 – Borjante

+0

我试图将提取移入componentWillReceiveProps,但它只是不断地进行API调用,直到错误来自过多的连接? – Phil

回答

1

使用componentWillReceiveProps工作对我来说是解决方案...

componentWillReceiveProps(nextProps){ 
    if(nextProps.dataFilter !== this.props.dataFilter){ 
     this.props.resultsFetchData('/api/deals/?data=' + nextProps.dataFilter); 
    } 
} 

handleChange(value, dispatcher){ 
    dispatcher(value.props["data-attr"]); 
}