首页 > 解决方案 > How can I have parent component to route to home page once child component has a success in Signup?

问题描述

I want my parent component App.js to route to '/home' if the child component LoginApp has a response back. (All validation happening is server side hence response will only comeback if authentication succeeds).

// Child Component

 const LoginApp = () => {
  const signupWasClickedCallback = (data) => {
console.log(data);


// ----- Adding Favourites
axios.post('/api/account/signup', data)
  .then(function (res) {
    console.log(res);

  })
  .catch(function (err) {
    console.log(err);
  });

 };
    const loginWasClickedCallback = (data) => {
   console.log(data);

axios.post('/api/account/signin', data)
  .then(function (res) {
    console.log(res);
  })
  .catch(function (err) {
    console.log(err);
  });
  };

return (
<div className="loginWrapper">
  <ReactSignupLoginComponent
    title="Welcome to KidKlub!"
    handleSignup={signupWasClickedCallback}
    handleLogin={loginWasClickedCallback}
  />
</div>
);


  };


export default LoginApp;




  // Parent Component

  class App extends Component {
   render() {
     return (
    <Router>
    <div>
      <Route exact path="/" component={LoginApp} />
      <Route exact path="/home" component={Home} />
    </div>
  </Router>
      );
       }
  }

 export default App;

标签: reactjsreact-routerreact-router-v4bcryptmern

解决方案


你可以这样做:

.then(function (res) {
console.log(res);
props.history.push('/home');
})
.catch(function (err) {
console.log(err);
props.history.push('/');
});

从 react-router-dom 使用 withRouter

import { withRouter } from 'react-router-dom';

用 withRouter 包装你的组件

export default withRouter(LoginApp);

推荐阅读