React Native-将父级状态传递给子级时遇到麻烦 [英] React Native - Trouble passing parent's state to child

查看:66
本文介绍了React Native-将父级状态传递给子级时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React新手遇到一些问题,这些问题从父级组件(在本例中为 App )传递状态和功能,而从子级组件( Main )。我确定这是一两个非常简单的错误,我在哪里绊倒了?

a React newbie having some issues passing down states and functions from Parent Component (App in this case) and accessing from Child Components (Main in this case). I'm sure it's one or two really simple mistakes, where am I getting tripped up?

这是项目结构:

App
 |__ Rootstack
       |
       |__Favorites
       |__Main

这是简化后的代码:

class Main extends React.Component {
  render() {
      return (
      <View>
         <Text>{this.props.favoritesList.length}</Text>
         <Card>
              onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
         </Card>
      </View>
        );
    }
}

class Favorites extends React.Component {
          ....
    }

const RootStack = StackNavigator(
  {
    Main: {
      screen: Main},
    Favorites: {
      screen: Favorites}
  },
  {
    initialRouteName: 'Main'
  }
);


export default class App extends Component<{}> {
  constructor(props) {
      super(props);
      this.state = {
        favoritesList: []
      };
    this.updateArr = this.updateArr.bind(this); //don't know if this is necessary?
    }

  updateArr=()=>{this.setState({ favoritesList: 
      [...this.state.favoritesList, 'new value']})};

  render() {
      return <RootStack {...this.state} updateArray={this.updateArr}/>;
    }
  }

我得到的错误是-有什么想法吗?

Error I'm getting is -- any ideas? Thanks in advance!

推荐答案

1-

这是不正确的

       <Card  ... props should be here!!---  >
          onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
     </Card>

正确的答案是:

     <Card  
       onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
      >
    </Card>

错误的含义是Card的子对象应该是对象而不是.....

The meaning of the error is that the child of Card is expected to be an object and not .....

2-

this.updateArr = this.updateArr .bind(this); 是不必要的,因为 updateArr =()=> ... 用es6编写

this.updateArr = this.updateArr.bind(this); is not necessary since updateArr = () => ... is written in es6

这篇关于React Native-将父级状态传递给子级时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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