react+redux 数据异步问题

新手上路,请多包涵

使用react+redux的一个项目中,使用到了chosen插件,在componentDidMount()中使用$(‘xxx’).chosen(),那么问题来了,从其他路由进到这个页面,数据可以正常传输过来,重新刷新这个页面之后,使用chosen插件的地方的数据没有到达(因为异步,使用chosen()的方法的时候数据没有请求过来),未使用chosen的地方数据正常,请问怎么解决呢?不使用setTimeout()这个方法的话

__chosen__ = (ctx, id) => {
    $('#' + id).chosen().change(function () {
        let v = $(this).val();
        ctx.setState({ [id] : (v && v.length>0) ? v : null });
        ctx.search();
    });
};
componentDidMount() {
    this.__chosen__(this, 'brand');
    this.__chosen__(this, 'team');
}

render() {
    const {brands, teams} = this.props;

    //console.log(brands)

    let brandList = brands.map(brand => {
            return (<option key={'b'+brand._id} value={brand._id}>{brand.name}</option>);
        });
    let teamList = teams.map(team => {
            return (<option key={'t'+team._id} value={team._id}>{team.name}</option>);
        });

    return (
        <div className="row" style={{marginLeft: '10%'}}>
            <div className="col-xs-6 col-sm-3">
                <div className="form-group">
                    <select id="brand" className="form-control" style={{width:'100%'}}>
                        <option value="">品牌</option>
                        {brandList}
                    </select>
                </div>
            </div>
            <div className="col-xs-6 col-sm-3">
                <div className="form-group">
                    <select id="team" className="form-control" style={{width:'100%'}}>
                        <option value="">客户团队</option>
                        {teamList}
                    </select>
                </div>
            </div>
    )
}
阅读 2.1k
2 个回答

{brands ? brandList : null}

生命周期方法 void componentWillReceiveProps(nextProps)

props是父组件传递给子组件的。父组件发生render的时候子组件就会调用componentWillReceiveProps(不管props有没有更新,也不管父子组件之间有没有数据交换)。

这个方法在异步完成 props(数据)传递给组件的时候被调用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题