Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - React-router - How to pass data between pages in React?

I am working on a project where I have to pass data from one page to another. For example, I have data on the first page.

let data = [
  {id:1, name:'Ford', color:'Red'},
  {id:2, name:'Hyundai', color:'Blue'}
]

Here is the first component page where I render this list of data with the name.

class ListDetail extends Component {
    constructor();
    handleClick(data){
    console.log(data);
  }
  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <ul>
          {data.map((data,i) => {
            return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>
          })}
        </ul>
      </div>
    );
  }
}

I want to pass this data to the next page where I need this data and more data than this. I am using React Router 4. Any suggestion or help would be helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on. See the example below.

Using the <Link /> component:

<Link
  to={{
    pathname: "/page",
    state: data // your data array of objects
  }}
>

Using history.push()

this.props.history.push({
  pathname: '/page',
    state: data // your data array of objects
})

Using either of the above options you can now access data on the location object as per the below in your page component.

render() {
  const { state } = this.props.location
  return (
    // render logic here
  )
}

You can see an example of how to pass a value along with a route in another example here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...