【问题标题】:How do I pass props from a header component to another unrelated container如何将道具从标头组件传递到另一个不相关的容器
【发布时间】:2018-08-19 03:11:41
【问题描述】:

我正在使用 React-router-dom 在组件之间进行切换,如下所示。

<Router>
        <div>
          <Header />
          <NavigationBar />
          <Switch>
            <Route exact path="/" component={Home} />
            <Route exact path="/home" component={Home} />
            <Route exact path="/about" component={About} />
            <Route path="/concepts" component={ConceptBox} />
            <Route path="/products" component={ProductBox} />
            <Route component={NotFound} />
          </Switch>
          <Footer />
        </div>
      </Router>

&lt;Header /&gt; 组件内,我有一个登录部分,用户可以在其中登录。它连接到 MongoDB 并返回包含数组的响应。

onSubmit = () => {
  if (this.state.email.trim() !== "" &&
  this.state.password.trim() !== "") {
    axios.post("http://localhost:3001/api/login", { email: this.state.email, password: this.state.password })
      .then((response) => {
        console.log(response)

我的快速登录路径如下:

router.route('/login')
.post(function(req, res){
  var email = req.body.email;
  var password = req.body.password;

  Member.authenticate(email, password, function (error, user) {
        if (error || !user) {
          var err = new Error('Wrong email or password.');
          res.send(err);

        } else {
          console.log("I have your response now");
          return res.send(user)

        }
  });

我想在 Home 组件的响应中使用这个数组。 我很困惑是否应该使用 reduxJS 或 cookie 来存储这些信息并在不同的组件中检索它?或者有没有一种巧妙的方法来检索我的

【问题讨论】:

    标签: javascript reactjs express react-router axios


    【解决方案1】:

    您可以将此数组存储为主要组件状态的一部分。这称为Lifting state up

    因此,包含路由的组件将具有接收数组作为参数并更新状态的功能。此状态将作为道具传递给您的 Home 组件。

    您的console.log(response) 将被替换为对此函数的调用。

    希望这会有所帮助! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-25
      • 2019-09-27
      • 2019-05-17
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      相关资源
      最近更新 更多