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