React-router-如何在React中的页面之间传递数据? [英] React-router - How to pass data between pages in React?

查看:31
本文介绍了React-router-如何在React中的页面之间传递数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,我必须将数据从一页传递到另一页.例如,我在第一页上有 data .

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>
    );
  }
}

我想将此数据传递到下一个页面,在该页面上我需要该数据以及比此更多的数据.我正在使用React Router4.任何建议或帮助都会有所帮助.

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.

推荐答案

您可以使用react-router中的Link组件并将 to = {} 指定为对象,并在其中将路径名指定为路由要去.然后添加一个变量,例如 data 保存要传递的值.请参见下面的示例.

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.

使用< Link/> 组件:

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

使用 history.push()

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

使用上述两个选项之一,您现在可以按照页面组件中的以下内容访问位置对象上的 data .

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.

这篇关于React-router-如何在React中的页面之间传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆