Redux集成

博客介绍了在app中集成Redux和React Navigation的方法,指出这和未使用React Navigation时差别不大,给出了完整示例链接。还说明了如何使用connect方法关联组件与store,将state作为参数传递到页面,以及在screen中使用setParams方法让title随store更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在app中集成Redux和React Navigation是一件很容易的事情,它基本和没有使用React Navigation时差不多。下面的例子展示了如何去使用它,并且最后给出了一个完整的例子https://snack.expo.io/@react-navigation/redux-example.其中最重要的代码片段就是下面这一段了

let RootStack = createStackNavigator({
  Counter: CounterContainer,
  StaticCounter: StaticCounterContainer,
});

let Navigation = createAppContainer(RootStack);

// Render the app container component with the provider around it
export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Navigation />
      </Provider>
    );
  }
}

注意我们要将组件从createAppContainer中返回,并且用Provider将其包裹住。这样你就可以在你的App中随意使用connect方法了。

关于navigationOptions

好吧 这里的资料并不完整,我们假设你想要访问Redux stroe中的state,来更改其title。那么你要怎么做呢?这里有一堆options

假设我们想要计算数值然后用其更改title。

首先我们要使用connect方法

创建一个组件,将其用connect与store关联,然后赋值给组件中的title。

class Count extends React.Component {
  render() {
    return <Text>Count: {this.props.value}</Text>
  }
}

let CountContainer = connect(state => ({ value: state.count }))(Count);

class Counter extends React.Component {
  static navigationOptions = {
    title: <CountContainer />
  };

  /* .. the rest of the code */
}

将state作为参数传递到页面中

如果你不想更改它的值,你可以仅仅将其作为参数从组件传递到页面中。

<Button
  title="Go to static count screen"
  onPress={() =>
    this.props.navigation.navigate('StaticCounter', {
      count: this.props.count,
    })
  }
/>

class StaticCounter extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('count'),
  });

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          {this.props.navigation.getParam('count')}
        </Text>
      </View>
    );
  }
}

在你的screen中使用setParams方法

让我们来更改StaticCounter。

class StaticCounter extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('count'),
  });

  componentDidMount() {
    this.updateCount();
  }

  componentDidUpdate() {
    this.updateCount();
  }

  updateCount() {
    this.props.navigation.setParams({ count: this.props.count });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          {this.props.navigation.getParam('count')}
        </Text>
      </View>
    );
  }
}

现在无论store如何更新count的值,title都会跟着自动更新。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值