簡體   English   中英

正在更改Redux狀態,但使用mapStateToProps時道具未定義

[英]Redux state is being changed but props are undefined when using mapStateToProps

我在我的應用程序中使用React-redux,我遇到了這個問題,我使用connect(mapStateToProps,mapDispatchToProps)(Component)並且能夠成功地使用映射的調度來操作redux狀態。 使用開發工具我看到狀態已成功更改,但映射的props在任何組件中始終未定義。

我正在嘗試的示例組件:

class DashboardPage extends React.Component {
  componentWillMount() {
    console.log(this.props.idToken);
  }
  render() {
    return (
        <div>
            <div className="dashboard-container">
                <p>{this.props.idToken}</p>

                <button onClick={() =>  {this.props.logout()}}>
                    LOGOUT
                </button>
            <button onClick={() =>  {browserHistory.push('/app/play')}}>
                    PLAY
                </button>
            <button onClick={() =>  {this.props.setIsLoading(true)}}>
                    TEST
                </button>
            </div>
        </div>
    );
  }
}

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

export default connect(mapStateToProps, { logout, setIsLoading })(DashboardPage);

但是,這之前一直在努力。 我暫時從代碼中休息了一段時間,所以我不記得我改變了什么來打破這個,但我很確定它與React路由器有關,所以這里是我的路線:

export default (
    <Route path="/" component={App}>
        <Route path="app" component={Authorized}>
            <IndexRedirect to="/app/dashboard"/>
            <Route path="dashboard" component={DashboardPage} />
            <Route path="play" component={PlayPage}/>
        </Route>
        <Route path="login" component={Login} />
    </Route>
);

我基本上使用App作為主容器,我在其中調用thunk動作來檢查localStorage中是否有令牌,然后如果是,則重新應用令牌狀態的調用和操作(成功登錄時調用相同的操作)。 在重新應用狀態之前,此操作會將用戶重定向到/app/dashboard ,如果localStorage中沒有保存憑據,則應用會自動重定向到/login

我的index.js

const appRoot = document.getElementById('app-root');

const store = createStore(reducers, compose(
    applyMiddleware(thunk),
    window.devToolsExtension ? window.devToolsExtension() : f => f
));

ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>
  , appRoot);

我有什么錯誤的路由,這使得mapStateToProps沒有正確返回道具?

在此先感謝您的幫助。

編輯:我剛剛編輯了我的mapStateToProps ,以查看狀態是否通過:

const mapStateToProps = (state) => {
  console.log(state);
  return {
    idToken: state.idToken,
  };
};

並且日志輸出undefined

當您更新狀態時,我覺得您沒有在reducer中添加以前的狀態。 例如,如果您的新狀態是return {action.something},那么它可能是{... state,action.something}。 我有這樣的問題。 我不是專家,仍在工作和學習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM