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

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

问题描述

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

让数据= [{id:1, name:'Ford', color:'Red'},{id:2, name:'Hyundai', color:'Blue'}]

这是我用名称渲染此数据列表的第一个组件页面.

class ListDetail extends Component {构造函数();句柄点击(数据){控制台日志(数据);}使成为() {返回 (<div><Hello name={this.state.name}/><ul>{data.map((data,i) => {return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>})}

);}}

我想将此数据传递到下一页,在那里我需要此数据以及比这更多的数据.我正在使用 React Router 4.任何建议或帮助都会有所帮助.

解决方案

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

使用 组件:

<链接到={{路径名:/页面",state: data//你的对象数据数组}}>

使用history.push()

this.props.history.push({路径名:'/页面',state: data//你的对象数据数组})

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

render() {const { state } = this.props.location返回 (//在这里渲染逻辑)}

您可以在此处的另一个示例中查看如何将值与路由一起传递的示例.

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.

解决方案

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.

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

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