从组件React Native中访问状态

时间:2018-04-15 09:50:07

标签: javascript reactjs react-native components

我是一个相当新的回应原生和在我使用RkButton的应用程序上工作,然后在单击按钮时更新状态。代码是这样的。



render() {
    const { user } = this.props;

    let navigate = this.props.navigation.navigate;

    let items = MainRoutes.map(function (route, index) {
      return (
        <RkButton
          rkType='square'
          key={index}
          onPress={() => {
              this.setState({
                redeem: true
              });
          }}>
        </RkButton>
      )
    });

      return (
        <View style={{flex: 1,}}>
            <ScrollView
              alwaysBounceVertical
              overScrollMode={"always"}
              style={{flex: 1, backgroundColor: 'white'}}
              refreshControl={
                  <RefreshControl
                  refreshing={this.state.refreshing}
                  onRefresh={() => this.handleRefresh()}
                  />
              }
              contentContainerStyle={styles.rootContainer}>
                {items}
            </ScrollView>
          </View>
      )
}
&#13;
&#13;
&#13;

我得到了'this.setState不是函数&#39;,因为我已经使用了UIKitten库中的代码,我并不完全熟悉它。我非常确定这与ES6有关,或者是我对组件如何工作的误解。

有人可以启发我吗?

3 个答案:

答案 0 :(得分:3)

你在这里松开了组件上下文:

  // Component context
  function (route, index) {
    // Functions context

将其更改为:

  (route, index) => {

答案 1 :(得分:2)

问题是用关键字function声明的函数有自己的上下文this。您需要使用箭头函数来访问父上下文:

let items = MainRoutes.map((route, index) => {
  return (
    <RkButton
      rkType='square'
      key={index}
      onPress={() => {
          this.setState({
            redeem: true
          });
      }}>
    </RkButton>
  )
});

答案 2 :(得分:0)

您应该保留的副本,并在任何其他功能中使用它。在需要时,如第3行所述。

所以你的代码有一些小改动

render() {
    const { user } = this.props;
    let self=this;

    let navigate = this.props.navigation.navigate;

    let items = MainRoutes.map(function (route, index) {
      return (
        <RkButton
          rkType='square'
          key={index}
          onPress={() => {
              self.setState({
                redeem: true
              });
          }}>
        </RkButton>
      )
    });

      return (
        <View style={{flex: 1,}}>
            <ScrollView
              alwaysBounceVertical
              overScrollMode={"always"}
              style={{flex: 1, backgroundColor: 'white'}}
              refreshControl={
                  <RefreshControl
                  refreshing={this.state.refreshing}
                  onRefresh={() => this.handleRefresh()}
                  />
              }
              contentContainerStyle={styles.rootContainer}>
                {items}
            </ScrollView>
          </View>
      )
}
相关问题