React history.push() not rendering new component

前端 未结 5 1157
梦谈多话
梦谈多话 2021-01-02 09:31

I have a React.js project with a simple sign in function. After the user is authorized, I call history.push method which changes the link in the address bar but does not ren

5条回答
  •  一向
    一向 (楼主)
    2021-01-02 09:39

    If anyone is interested - this was happening because the app was rendering before the history was pushed. When I put the history push into my action but just before the result is converted into JSON, it started working since now it pushes history and only then renders the App.

    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);
          }
        });
      });
    

提交回复
热议问题