【问题标题】:mapStateToProps not called at the first call to the component首次调用组件时未调用 mapStateToProps
【发布时间】:2016-08-10 14:32:44
【问题描述】:

我将 observable-react-project 转换为 Redux。我有主容器 - App.js 和他包含下一个方法:

handleDone () {
    this.setState({ showPLock: false });
}

render () {
    return (
        <div className="mainContainer">
            {this.props.children}
            {
                this.state.showPLock
                    ? <PCode handleDone={this.handleDone.bind(this)}/>
                    : null
            }
        </div>
    );
}

在第一次启动应用中显示PLock: true。 代码 PCode:

class PCode extends Component{
constructor (props) {
    super(props);

    this.state = {
        passcode: ''
    };
}

render () {
    //something doing
}
}

PCode.contextTypes = {
   router: PropTypes.object.isRequired,
   store: PropTypes.object.isRequired
};

PCode.propTypes = {
    dispatch: PropTypes.func.isRequired,
};

function mapStateToProps(stateStore) {
    const { authReducer } = stateStore;
    if (authReducer.pcode !== null) {
        //something return
    }
}

export default connect(mapStateToProps)(PCode);

调用 mapStateToProps 时出现问题。在组件命中时不会立即调用他。因此,如果我调用 render 一些东西,例如:

const { data } = this.props;

当然会发出undefined。

为什么第一次调用组件时没有调用 mapStateToProps?

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    我正在努力。我说为了简化这个问题,我扩展了 React.Component... 不是这个检查问题!

    【讨论】:

      【解决方案2】:

      是的,mapStateToProps 应该在组件第一次挂载时执行。

      要检查两件事:

      • 您确定没有调用该函数吗?确保从 mapStateToProps 返回一个对象,即使它只是一个空的 {}
      • PCode 类可能应该扩展 React.Component: class PCode extends React.Component {}

      【讨论】:

      • 1) 调用pCode mapStateCalled 中的函数,调用后调用mapStateCalled App.js 2) 检查,好的
      • 那么目前的问题是什么?请更新您的代码以显示您现在的位置。
      • 都是同样的问题。 1 检查不正确,因为我在调试此功能时做了标记。 2 检查 - 好的,但我已经扩展了自己的 BaseComponent,而他扩展了 React.Component。轻松更新“要显示的代码”扩展 React.Component
      • 您能否尝试扩展React.Component 而不是BaseComponent,这将表明BaseComponent 是否存在干扰。同时发布BaseComponent 的骨架可能会有所帮助。
      猜你喜欢
      • 2019-09-28
      • 2020-07-23
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多