【问题标题】:React Native - Trouble passing parent's state to childReact Native - 将父母的状态传递给孩子的麻烦
【发布时间】:2018-08-04 19:53:48
【问题描述】:

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

这是项目结构:

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}/>;
    }
  }

我得到的错误是——有什么想法吗?提前致谢!

【问题讨论】:

  • 您正在尝试通过导航器发送道具并通过您的组件访问它。你不能通过这种方式通过导航器发送道具。看看this,它可能会对你有所帮助。
  • 首先不需要绑定箭头函数,其次您将道具传递给无状态组件,并且导航器也无法直接接收道具。

标签: javascript reactjs react-native components parent-child


【解决方案1】:

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的孩子应该是一个对象而不是.....

2-

this.updateArr = this.updateArr.bind(this); 不是必需的,因为updateArr = () =&gt; ... 是用 es6 编写的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2018-06-29
    • 1970-01-01
    • 2017-01-17
    • 2016-12-25
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    相关资源
    最近更新 更多