簡體   English   中英

ReactJS如何在頁面之間傳輸數據?

[英]ReactJS How to transfer data between pages?

我還是React的新手。

我想知道,如何將數據從讓我們說“主頁”轉移到另一頁以顯示結果?

我認為它與道具有關? 但我不完全確定。

我的MainPage具有輸入/選擇標記,其中包含名稱,值,用戶和日期的選擇。

我希望能夠獲取所有這些信息並將其輸出到另一個名為“DisplayResults”的頁面中,並可能將數據用於其他內容,也許可以創建一個包含該信息的表。

非常感謝您的幫助!

這是我的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

一個簡單的方法是讓您的Main組件將這些數據保存在其狀態中,並將其作為道具傳遞給其他頁面。 由於您正在使用react-router您需要克隆Main組件中的this.props.children以添加其他道具,例如數據和設置數據的函數。

您的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>
   }
}

從技術上講,React創建單個頁面應用程序,因此沒有其他頁面可以傳遞數據。

但是,我相信您可能正在談論將數據傳遞到components 我總是將我的React應用程序構建到containercomponent文件夾中。 容器文件夾是所有邏輯組件所在的位置,組件文件夾是所有UI組件所在的位置。

使React如此直觀的一個原因是,您可以通過props輕松地將數據從父組件傳遞到子組件。 換句話說,我的邏輯組件通過props將數據傳遞給UI組件。

例如,假設我希望我的邏輯組件Dashboard將組織數據傳遞給我的UI組件MyChildComponent ,我會這樣做:

containers/DashBoard/index.js

export class DashBoard extends React.Component { // eslint-disable-line react/prefer-stateless-function

  constructor(props) {
    super(props);
    this.state = {
      organizations: null,
    };
    this.rowCallback = this.rowCallback.bind(this);
  }

  render() {
    <MyChildComponent orgs={this.state.organizations} />
  }
}

components/MyChildComponent/index.js

export class MyChildComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render(){
    <div>
      {this.props.orgs}
    </div>
  }
}

這只是處理傳入數據的一種方法。 您還可以在邏輯組件之間路由時傳入值,或者使用redux庫(如redux來創建狀態變量等。

請注意我的代碼摘錄使用es6,需要一個babel編譯器。 我也更喜歡在可能的情況下使用UI組件的功能,因為我認為這是React Way

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM