【问题标题】:React: reading data passed as parameter in history.pushReact:读取在 history.push 中作为参数传递的数据
【发布时间】:2019-02-08 11:23:28
【问题描述】:

我是新手,我正在尝试将一些数据作为参数发送到history.push

基本上,我在单击按钮时调用一个方法,在该方法内部我调用一个 api。如果我得到成功响应,我会重定向到其他页面,并且我还需要传递一些数据。

下面是我的代码:

class Login extends Component  {

  constructor(props) {
    super(props);
    this.state = {
      enteredName: null,
      enteredPwd: null,
      rescode: null,
      userName: null,
      formatDesc: null,
      userFormat : null,
      success: false,
      responseJson : null,
    };
  }

  state = {
    enteredName: null,
    enteredPwd: null,
    rescode: null,
    userName: null,
    formatDesc: null,
    userFormat : null,
    success: false,
    responseJson : null,
  }
    render=() =>{

        return (
          <Router>
          <div id= "login-page">
            <div className="back-image" style={{height:"100vh"}}>
              <div className="container">
                <form className="form-login" action="index.html">
                  <h2 className="form-login-heading">sign in now</h2>
                  <div className="login-wrap">
                    <label>User ID</label>
                    <input type="text" ref="usrname" className="form-control" placeholder="User ID" autofocus/>
                    <br/>
                    <label>Password</label>
                    <input type="password" ref = "password" className="form-control" placeholder="Password"/>
                    <br/>
                    <a  className="btn btn-theme btn-block" onClick={this.login.bind(this)}><i className="fa fa-lock mr-10"/>SIGN IN</a>
                    <Dialog ref={(component) => { this.dialog = component }} />
                  </div>
                </form>
              </div>
            </div>
          </div>
          </Router>
        );

}
login = (e) => {
  e.preventDefault();

  fetch('some url', {
    method: 'POST',
    body: JSON.stringify({
      "userId": this.refs.usrname.value,
      "password": this.refs.password.value
    })
  })
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(`response: ` , responseJson)
      if (responseJson.errorCode === '00') {
        this.setState({ rescode: responseJson.errorCode })
        this.setState({ userName: responseJson.userName })
        this.setState({ formatDesc: responseJson.formatDesc });
        this.setState({userFormat : responseJson.userFormat});
        this.setState({success : true});
        this.setState({responseJson: responseJson});
        this.props.history.push(
          '/Taskactive',
          {
            role_id : this.userFormat,
            userName : this.userName
          }
        );
      }
      else {
        alert("Error Logging in.." + responseJson.errorMsg);
        this.refs.usrname.value = "";
        this.refs.password.value = "";
      }

    })
    .catch((error) => {
      console.error(error);
    });

  this.refs.usrname.value = "";
  this.refs.password.value = "";
}

所以到目前为止一切都很好,但现在我需要在下一页读取传递的数据,即 role_iduserName,即 Taskactive .那么我们如何读取Taskactive.jsx 中的这些数据呢?

【问题讨论】:

    标签: reactjs react-router react-router-v4 react-router-dom react-16


    【解决方案1】:

    好的,在挣扎了 4 天并在 Luna 和 JupiterAmy 给出的答案周围抽搐之后,这对我有用:

    Login.jsx

    里面
    this.props.history.push({
              pathname : '/Taskactive',
              state :{
              role_id : responseJson.userFormat,
              userName : this.userName,
              userid: this.refs.usrname.value
              }
              } 
            );
    

    Taskactive.jsx

    this.props.location.state.role_id
    

    希望这可以帮助将来的人。

    【讨论】:

      【解决方案2】:

      改一下

      this.props.history.push(
                '/Taskactive',
                {
                  role_id : this.userFormat,
                  userName : this.userName
                }
              );
      

      到这里:

      this.props.history.push({
                pathname: '/Taskactive',
                appState: {
                  role_id : this.userFormat,
                  userName : this.userName
                }
              });
      

      在您为路径/Taskactive 渲染的组件内,您可以访问 this.props.location.appState.role_id 或 this.props.location.appState.userName 等值 您还可以根据自己的意愿更改对象的名称(我保留为状态)。

      希望这会有所帮助。

      【讨论】:

      • 您好 Chandrani,请立即尝试,出现语法错误。我现在已经更新了我的答案。
      • 我得到 TypeError: Cannot read property 'role_id' of undefined 当我尝试像 alert("gettroles called "+ this .props.location.appState.role_id);
      • 检查您的反应开发工具是否有 appState 可用作位置内的道具。
      【解决方案3】:

      如果它是使用 react-router 渲染的组件,则传递的内容在组件 props 内。

      console.log(this.props.match.params)
      

      据我所见,您的路由器配置错误。登录应该是&lt;Router&gt; 的子级,根本不应该是容器路由器。

      示例配置:

      <Router>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route path="/login" component={Login} />
          <Route path="/signup" component={Signup} />
          <Route path="/restore-password" component={RestorePass} />
          <Route path="/forgot-password" component={ForgotPass} />
        </Switch>
      </Router>
      

      【讨论】:

      • 我尝试像 this.props.role_id 一样读取 Taskactive.jsx 中的 role_id,但响应中我得到了未定义
      • @ChandraniChatterjee 不,它不是 this.props.role_id。它在 this.props.match.params 下。 console.log ,你会看到的。
      • 控制台中仍未定义
      • @ChandraniChatterjee 是您的组件,您在其中控制台日志由 react-router 呈现?它不应该是它工作的子组件。你到底想记录什么?尝试准确记录我写的内容并检查它的内容
      • 我在日志中未定义,Taskactive.jsx 不是 Login.jsx 的子节点
      猜你喜欢
      • 2018-02-20
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2022-11-20
      • 2021-06-06
      相关资源
      最近更新 更多