反应本机全局状态
React Native Global state
我在我的一个页面上设置了一个状态变量,但我希望该状态值也可以在另一个页面上访问。不太清楚这是如何实现的。
例如 mainpage.ios.js
var MainPage = React.createClass({
getInitialState: function() {
return {
value: 1
};
},
然后 otherpage.ios.js 我想根据上一页中已设置的值进行更新。通过标签栏选择不同的页面。所以基本上这个值在所有页面之间实际上是全局的。
没关系,我知道怎么做了。对于任何不知道的人,这就是我的做法。据我所知,没有全局状态,你只需要将道具传递给每个页面组件。
所以对于 mainpage.ios.js 你需要 otherpage.ios.js:
var OtherPage = require('./otherpage');
然后当您使用该元素时,您将包含 pass 道具:
<OtherPage value={2}/>
或
<OtherPage value={this.state.value}/>
然后在 otherpage.ios.js 上,您可以根据需要引用该变量:this.props.value.
要使用 React Native 在多个组件之间共享全局状态,您应该利用 Flux 实现。我个人更喜欢 redux,但你可以使用任何你喜欢的。这是一个使用 React Native 的 redux 示例:https://github.com/alinz/example-react-native-redux
我在我的一个页面上设置了一个状态变量,但我希望该状态值也可以在另一个页面上访问。不太清楚这是如何实现的。
例如 mainpage.ios.js
var MainPage = React.createClass({
getInitialState: function() {
return {
value: 1
};
},
然后 otherpage.ios.js 我想根据上一页中已设置的值进行更新。通过标签栏选择不同的页面。所以基本上这个值在所有页面之间实际上是全局的。
没关系,我知道怎么做了。对于任何不知道的人,这就是我的做法。据我所知,没有全局状态,你只需要将道具传递给每个页面组件。
所以对于 mainpage.ios.js 你需要 otherpage.ios.js:
var OtherPage = require('./otherpage');
然后当您使用该元素时,您将包含 pass 道具:
<OtherPage value={2}/>
或
<OtherPage value={this.state.value}/>
然后在 otherpage.ios.js 上,您可以根据需要引用该变量:this.props.value.
要使用 React Native 在多个组件之间共享全局状态,您应该利用 Flux 实现。我个人更喜欢 redux,但你可以使用任何你喜欢的。这是一个使用 React Native 的 redux 示例:https://github.com/alinz/example-react-native-redux