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

标签 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);

我的Action Creator:

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) 方法推送历史记录,则会出现同样的问题 - 它会更改地址但不会呈现新组件。有人可以解释为什么会发生这种情况以及如何解决吗?

最佳答案

如果有人感兴趣 - 发生这种情况是因为应用程序在推送历史记录之前正在呈现。当我将历史推送放入我的操作中但就在结果转换为 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);
      }
    });
  });

关于javascript - React history.push() 不呈现新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925939/

相关文章:

php - 为什么即使找不到匹配项,switch 语句也会执行 case block ?

javascript - 不变违规 : ViewPropTypes has been removed from React Native

javascript - URLSearchParams 返回空对象

javascript - 提交后 React.js "hide element and reveal next element"

javascript - React Router 不加载外部 html 文件

javascript - 使用 Angular 向单个列表项添加功能

javascript - 如何在reactjs中为数字输入字段设置默认值?

javascript - 我如何使用react-semantic-ui和功能组件制作排序表?

reactjs - 使用 firebase auth 刷新 protected 路由 React Router

reactjs - React Router Switch 和确切路径