React history.push()不呈现新组件

时间:2018-06-19 10:17:03

标签: javascript reactjs react-router-v4

美好的一天,大家好!

我有一个带有简单登录功能的React.js项目。在用户被授权后,我调用history.push方法,该方法更改地址栏中的链接但不呈现新组件。 (我使用BrowserRouter)

我的 index.js 组件:

ReactDOM.render(
  <Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
    <BrowserRouter>
      <Main />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

我的 Main.js 组件:

const Main = (props) => {
  return (
    <Switch>
      <Route exact path="/" component={Signin} />
      <Route exact path="/servers" component={Servers} />
    </Switch>
)}

export default withRouter(Main);

我的行动创作者

export const authorization = (username, password) => (dispatch) =>
  new Promise ((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password,
      })
    }).then( response => {
      if (response.ok) {
          response.json().then( result => {
            console.log("API reached.");
            dispatch(logUserIn(result.token));
            resolve(result);
        })
      } else {
        let error = new Error(response.statusText)
        error.response = response
        dispatch(showError(error.response.statusText), () => {throw error})
        reject(error);
      }
    });
  });

我的 Signin.js 组件:

 handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token); //I do get "success" in console
      this.props.history.push('/servers') //Changes address, does not render /servers component
    });

  }

const mapActionsToProps = {
  onLoginRequest: authorization
}

最奇怪的是,如果我将handleSubmit()方法改为此 - 一切都运行良好:

  handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token);
      //this.props.history.push('/servers')
    });
    this.props.history.push('/servers')
  }

如果我尝试从componentWillReceiveProps(newProps)方法推送历史记录,则会出现同样的问题 - 它会更改地址但不会呈现新组件。有人可以解释为什么会发生这种情况以及如何解决它?

谢谢!

5 个答案:

答案 0 :(得分:4)

如果有人感兴趣-发生这种情况是因为应用程序在推送历史记录之前就已呈现。当我将历史记录推入到动作中,但在将结果转换为JSON之前,它就开始工作,因为现在它会推入历史记录,然后才呈现该应用程序。

export const authorization = (username, password, history) => (dispatch) =>
  new Promise ((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password,
      })
    }).then( response => {
      if (response.ok) {

          //################################
          //This is where I put it

          history.push("/servers");

          //################################

          response.json().then( result => {
            dispatch(logUserIn(result.token));
            resolve(result);
        })
      } else {
        let error = new Error(response.statusText)
        error.response = response
        dispatch(showError(error.response.statusText), () => {throw error})
        reject(error);
      }
    });
  });

答案 1 :(得分:4)

您需要使用Router才能在每个使用“推”的组件中使用this.props.history.push('/ page')

R CMD BATCH scriptName.r

这在使用push时很重要。

答案 2 :(得分:0)

不适用于此 - &gt;

handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token); //I do get "success" in console
      this.props.history.push('/servers') //Changes address, does not render /servers component
    });

  }

const mapActionsToProps = {
  onLoginRequest: authorization
}

因为这个handleSubmit方法你在promise中调用this.props.history.push()所以this指向Promise的实例而不是你当前的类实例。

试试这个 - &gt;

 handleSubmit(event) {

    event.preventDefault();
    const { history: { push } } = this.props;
    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token); //I do get "success" in console
      push('/servers') //Changes address, does not render /servers component
    });
  }

const mapActionsToProps = {
  onLoginRequest: authorization
}

现在在本声明中 - &gt;

 handleSubmit(event) {

    event.preventDefault();

    this.setState({ isLoading: true })

    const { username, password } = this.state;
    this.props.onLoginRequest(username, password, this.props.history).then(result => {
      console.log("Success. Token: "+result.token);
      //this.props.history.push('/servers')
    });
    this.props.history.push('/servers')
  }

您正在调用this.props.history.push(),因为它超出了承诺并且引用了Current Class实例。

答案 3 :(得分:0)

尝试使用自定义历史记录和路由器而不是BrowserRouter。安装历史记录后:

yarn add history

创建自定义浏览器历史记录:

import { createBrowserHistory } from "history";

export default createBrowserHistory();

在设置中使用路由器而不是BrowserRouter:

import history from "your_history_file";

ReactDOM.render(
  <Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
    <Router history={history}>
      <Main />
    </Router>
  </Provider>,
  document.getElementById('root')
);

或者如果您不想使用自定义历史记录文件并从那里导入,您可以直接在index.js中创建它:

import { createBrowserHistory } from "history";

const history = createBrowserHistory();

ReactDOM.render(
  <Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
    <Router history={history}>
      <Main />
    </Router>
  </Provider>,
  document.getElementById('root')
);

答案 4 :(得分:0)

首先,使用历史记录包创建一个历史记录对象:

// src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();

然后将其包装在主路由器组件中。

    import { Router, Route, Link } from 'react-router-dom';
    import history from './history';

    ReactDOM.render(
        <Provider store={store}>
          <Router history={history}>
            <Fragment>
              <Header />
              <Switch>
                <SecureRoute exact path="/" component={HomePage} />
                <Route exact path={LOGIN_PAGE} component={LoginPage} />
                <Route exact path={ERROR_PAGE} component={ErrorPage} />
              </Switch>
              <Footer />
            </Fragment>
      </Router>
    </Provider>)         

在这里,调度请求后,重定向到主页。

    function requestItemProcess(value) {
        return (dispatch) => {
            dispatch(request(value));
            history.push('/');
        };

    }   

应该会有所帮助:)