[英]React Native - Trouble passing parent's state to child
一個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}/>;
}
}
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 = () => ...
寫在es6中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.