React Native - Trouble passing parent's state

2019-08-29 04:10发布

问题:

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?

Here is the project structure:

App
 |__ Rootstack
       |
       |__Favorites
       |__Main

And here is the stripped down code:

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:

1-

This is not correct

       <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>

The correct answer is:

     <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>

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); is not necessary since updateArr = () => ... is written in es6