在React Router中使用渲染道具时,获取组件中未定义的道具

时间:2020-03-27 12:26:13

标签: reactjs react-router

我正在尝试实施密码重置,当前当用户单击发送到电子邮件的链接(嵌入有令牌和userId)时,他被重定向到更新密码页面。因此,在UpdatePassword组件中,我得到的道具是未定义的。这是代码。

App.js

  <Route
    path="/update-password"
    render={({ match }) => (
      <UpdatePassword
        userId={match.params.userId}
        token={match.params.token}
      />
    )}
  />

UpdatePassword是一个只有两个输入字段的简单组件:

import React, { Component } from "react"

class UpdatePassword extends Component {
  constructor(props) {
    super(props)
    this.state = {
      password: "",
      confirmPassword: "",
      isSubmitted: false
    }
  }

  handleChange = event => {
    const { name, value } = event.target
    this.setState({
      [name]: value
    })
  }

  render() {
    console.log(this.props)
    return (
      <div>
        <h2 style={{ textAlign: "center" }}>Update your password</h2>
        <div className="field">
          <p className="control has-icons-left has-icons-right">
            <input
              className="input"
              onChange={this.handleChange}
              name="password"
              value={this.state.password}
              type="email"
              placeholder="Enter new password"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-envelope"></i>
            </span>
            <span className="icon is-small is-right">
              <i className="fas fa-check"></i>
            </span>
          </p>
        </div>
        <div className="field">
          <p className="control has-icons-left has-icons-right">
            <input
              className="input"
              onChange={this.handleChange}
              name="confirmPassword"
              value={this.state.confirmPassword}
              type="email"
              placeholder="Confirm password"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-envelope"></i>
            </span>
            <span className="icon is-small is-right">
              <i className="fas fa-check"></i>
            </span>
          </p>
        </div>
        <button onClick={this.handleSubmit} className="button is-success">
          Submit
        </button>
      </div>
    )
  }
}

export default UpdatePassword

后端路由为router.post("/receive_new_password/:userId/:token", emailController.reveiveNewPassword)

1 个答案:

答案 0 :(得分:0)

我认为您对match有疑问。 params可以是undefined。试试这个:

<Route
    path="/update-password"
    render={(prop1, prop2) => {
    const { match } = prop1; 
    console.log(prop1, prop2, match);
    return (
      <UpdatePassword
        userId={match.params.userId}
        token={match.params.token}
      />
    )}
  />