ReactJS如何在页面之间传输数据? [英] ReactJS How to transfer data between pages?

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

问题描述

我还是React的新手.

I'm still new to React.

我想知道如何将数据从主页"传输到另一个页面以显示结果?

I was wondering, how do I transfer data from let's say "Main Page" to another page to display the results?

我认为这与道具有关?但是我不确定.

I think it has something to do with props? But I'm not entirely sure.

我的主页有输入/选择标签,其中包含名称,值,用户和日期的选择.

My MainPage has input/select tags that takes in name, value, selections from user and dates.

我希望能够获取所有这些信息,并将其输出到另一个名为"DisplayResults"的页面中,并可能将数据用于其他用途,或者使用信息创建一个表.

I want to be able to grab all those information and output it in another page called "DisplayResults" and maybe use the data for other things, maybe create a table with the information.

非常感谢您的帮助!

这是我的app.jsx

var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Main = require('Main');
var MainPage = require('MainPage');
var About = require('About');
// Load foundation
require('style!css!foundation-sites/dist/foundation.min.css')
$(document).foundation();
ReactDOM.render(
  <Router history={hashHistory}>
    <Route path="/" component={Main}>
      <Route path="about" component={About}/>
      <IndexRoute component={MainPage}/>
    </Route>
  </Router>,
  document.getElementById('app')
);

推荐答案

有几种不同的方法...好的选择是使用某些状态管理层,例如Redux或MobX

There are a few different ways... Good option would be to use some state management layer like Redux or MobX

一个简单的方法是让您的 Main 组件以状态保存这些数据,并将其作为道具传递给其他页面.由于您使用的是 react-router ,因此您需要在 Main 组件中克隆 this.props.children ,以添加其他道具例如数据和设置数据的功能.

A simple one is to have your Main component save those data in its state and pass it to the other pages as props. Since you're using react-router you'll need to clone the this.props.children in your Main component to add the additional props like the data and the function that sets the data.

您的 Main 组件可能看起来像

class Main extends Component {
   constructor(props) {
      this.state = {
         data: 'some default data',
      }
   }

   updateData(data) {
      this.setState({ data });
   }

   render() {
     return <div>
        <Header />
        {React.cloneElement(this.props.children, { data: this.state.data, setData: this.updateData })}
     </div>
   }
}

class MainPage extends Component {

   render() {
      return <div>
         <input type="text" onChange={e => this.props.setData({ field: e.target.value })} />
         <Link to="/DisplayResults">Go to Results</Link>
      </div>
   }
}

class DisplayResults extends Component {
   render() {
       return <div>
         {this.props.data.field}
       </div>
   }
}

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

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