反应路由器 4 和 props.history.push [英] React Router 4 and props.history.push

查看:18
本文介绍了反应路由器 4 和 props.history.push的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React 中有一些让我发疯的东西,我需要你的帮助.基本上,当用户单击我的个人资料"时,我想重定向到用户的个人资料.为此,我使用以下代码段

There's something driving me crazy in React, and I need your help. Basically, when the user clicks "My Profile", I want to redirect to the user's profile. To do that, I use the following snippet

viewProfile = () => {
    console.log('My USER ID: ', this.props.userId);
    this.props.history.push(`/profile/${this.props.userId}`);
}

这应该有效.但是,尽管单击我的个人资料"时 URL 会更改为正确的 URL,但该页面并未出现.它只是保留为旧页面.

This should work. However, although the URL is changing to the correct URL when 'My Profile' is clicked, the page isn't appearing. It just stays as the old page.

谷歌搜索了一段时间后,我知道这与redux有关......但是,我找不到解决方案.(this.props.userId 来自一个 Layout 组件,后者又从 redux store 中获取)

After googling for a while, I know it's something to do with redux ... However, I can't find a solution. (this.props.userId is coming from a Layout component, which is in turn getting it from redux store)

这是我的代码:

// React
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
// Redux
import { connect } from 'react-redux';
import * as actions from '../../../store/actions/';
// Containers and Components
   ...// more imports

const styles =  // styles

class NavBar extends Component {

  handleAuthentication = () => {
    if (this.props.isAuthenticated) {
      this.props.history.push('/logout');
    } else {
      this.props.history.push('/login');
    }
  };

  viewProfile = () => {
    console.log('My USER ID: ', this.props.userId);
    this.props.history.push(`/profile/${this.props.userId}`);
  };

  render() {
    let buttons = (
      <Auxillary>
        {this.props.isAuthenticated ? (
          <RaisedButton
            label="MY PROFILE"
            primary={true}
            style={styles.button}
            onClick={this.viewProfile} // THIS IS THE METHOD
          />
        ) : null}
        <RaisedButton
          backgroundColor={grey900}
          label={this.props.isAuthenticated ? 'LOGOUT' : 'LOGIN'}
          labelColor={grey50}
          style={styles.button}
          onClick={this.handleAuthentication}
        />
      </Auxillary>
    );

    let itemSelectField = null;
    if (this.props.location.pathname === '/items') {
      itemSelectField = (
        <ItemSelectField
          onSelectTags={tags => this.props.filterItemsByTagName(tags)}
        />
      );
    }
    let bar = null;
    if (
      this.props.location.pathname !== '/login' &&
      this.props.location.pathname !== '/register'
    ) {
      bar = (
        <AppBar
          style={styles.appBar}
          title={itemSelectField}
          iconElementLeft={
            <img style={styles.logoHeight} src={Logo} alt="logo" />
          }
          iconElementRight={buttons}
        />
      );
    }
    return <Auxillary>{bar}</Auxillary>;
  }
}

const mapDispatchToProps = dispatch => {
  return {
    filterItemsByTagName: selectedTags =>
      dispatch(actions.filterItemsByTagName(selectedTags))
  };
};

export default withRouter(connect(null, mapDispatchToProps)(NavBar));

您可以在此处找到整个应用程序:https://github.com/Aseelaldallal/boomtown/tree/boomtown-backend-comm

You can find the entire app here: https://github.com/Aseelaldallal/boomtown/tree/boomtown-backend-comm

试图解决这个问题我快疯了.帮助.

I'm going crazy trying to fix this. help.

推荐答案

你需要集成react-router-redux.

看起来更新的状态没有反映在容器中,因为 redux 做了浅层比较来检查组件是否需要更新.

Its look like the updated state is not reflecting in the container as redux do shallow comparison to check whether the component need to be update or not.

import {Router} from 'react-router-dom';
import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';

const history = createHistory()
const middleware = routerMiddleware(history)


const rootReducer = combineReducers({
    router: routerReducer,
  //other reducers
});

const store = createStore(rootReducer,applyMiddleware(middleware));

<Provider store={store}>
<ConnectedRouter>
 //routes
</ConnectedRouter>
</Provider>

另外,在reducers,添加这个片段.

Also,at reducers,add this snippet.

let updatedStore = JSON.parse(JSON.stringify(state));

这篇关于反应路由器 4 和 props.history.push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆