首页 > 解决方案 > React Redux:更新时组件内部内容之间的延迟

问题描述

我有一个组件,里面有 2 个组件:

MyComp {
    render ( 
       html of My Comp..
       <Loading show={this.props.isLoading}/>
       <ErrorMessage show={this.props.hasError}/>  
    )
}

接收数据时,显示Loading。加载完成后,它会收到如下信息:

{
   isLoading: false,
   hasError: true
}

但在屏幕上,加载在 hasError 显示前 2 秒关闭。

这两个组件都采用相同的策略构建:

class Loading extends Component {
    constructor(props) {
        super(props);
        this.state =  {isLoading : props.show};
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ isLoading: nextProps.show });
    }
    render() {
        if (this.state.isLoading) {
          return (
            <div className="loading">
              <div className="loading-message">
              Carregando...
              </div>
            </div>);
        }
        return ('');
    }
}

export default Loading;

标签: reactjsredux

解决方案


不完全是这个问题的答案,因为我不确定延迟来自哪里。

但是根据您的代码,我建议不要使用本地state并尝试将其与外部同步props
这可能会导致错误(可能与您的问题有关?),因为componentWillReceiveProps即使没有props收到新消息也会被调用,除了它自反应 V16.2 以来 处于弃用过程中。

相反,我会直接从this.props

class Loading extends Component {

    render() {
        if (this.props.isLoading) {
          return (
            <div className="loading">
              <div className="loading-message">
              Carregando...
              </div>
            </div>);
        }
        return ('');
    }
}

同样,不确定它是否与您的问题直接相关,但这是一种更好的做法。


推荐阅读