React JS:以编程方式使用 React-Router 发送道具

React JS: Programmatically use React-Router to send props

这个问题试图弄清楚的是什么很简单:

"Can I send props programatically from one scene to another, and if so, how?"

下面我提供了一组示例代码,希望有知识的人一劳永逸地解决这个问题。

App.js 文件:

const Main = () => (
    <main>
        <Switch>
            <Route exact path='/Job' component={Job}/>
            <Route path='/Preview' component={Preview}/>
        </Switch>
    </main>

Job.js:

长话短说,一旦用户点击提交,文件就会进行输入和输出,调用此函数:

 handleClick(){
    //The state I wish to pass: this.state.propToPass
    //my current implementation for moving to the correct scene:
    this.props.history.push('/Preview')

}

Preview.js

constructor(props){
    super(props)
    //console.log(the prop that has been sent)
}

我将永远感谢任何理解问题并能阐明我的困境的人。

非常感谢。

我强烈推荐使用 redux-form,因为它使用 reducer 来保存表单的状态。然后,在路由到所需的组件后,您还可以将该组件连接到表单状态以获取所需的信息。 它是一个强大的工具,可以帮助您管理表单的状态,听起来正是您所需要的。

这是一个 withRouter 的例子。 returns 附加路由器的子组件是一个高阶函数,因此您可以通过编程方式切换路由。

通过发送一个对象而不仅仅是一个字符串来找到答案。您可以通过在名为状态的对象中附加一个 属性 来指定要作为状态发送的数据,该对象将包含您要发送的数据。

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

class Test extends React.Component {
  _handleClick = () => {
    this.props.history.push({
      pathname: '/roster',
      state: {
        'hello': 'world',
      }
    });
  }
  render() {
    return (
      <button onClick={this._handleClick}>Go To Roster Programmatically</button>
    )
  }
}

export default withRouter(Test);