React子组件无法调用父组件setState问题求助
问题分析与解决方案
你遇到的核心问题是函数式组件和类组件的props访问方式混淆了,CrewsAdapter是一个函数式组件,不能用this.props来访问传入的props,直接用参数里的props即可。另外还有一个小变量声明的问题,我帮你一步步修正:
主要错误点
CrewsAdapter是函数式组件,函数组件接收的props是直接作为参数传入的,不需要通过this.props访问,这是导致undefined is not an object报错的根本原因。crewsNames变量没有用const声明,会隐式创建全局变量,不符合JS语法规范。
修正后的完整代码
const CrewsAdapter = props => { if(props.data.loading) { return <View><Text>Loading crews</Text></View> } if(props.data.getAllCrews) { // 给变量添加const声明,避免全局变量污染 const crewsNames= props.data.getAllCrews.map(crew => ({"value": crew.crewName})); return ( <View style={{ flexDirection: 'column', alignItems: 'center', backgroundColor: '#ffffff' }}> <View style={[styles.container, { flex: 0.25 }]}> <Text style={styles.headerText}>Crews</Text> </View> <View style={{ flexDirection: 'row' }}> <View style={{ flex: 0.9 }}> {/* 函数组件直接用props,去掉this */} <Dropdown label="Crews List" data={crewsNames} onChangeText={(value) => {props.stateHandler(value)}} /> </View> </View> <View style={{ flexDirection: 'row' }}> <Crew/> </View> </View> ); } return <View><Text>No data</Text></View> }; export default class CrewsScreen extends Component { constructor(props) { super(props); this.stateHandler = this.stateHandler.bind(this); this.state = { crewName: '', } } stateHandler(value){ this.setState({crewName: value}); } render() { const AllCrews = graphql(crewsList, {options: (props => ({}))})(CrewsAdapter); return ( <SafeAreaView style={styles.screen}> <ToolBar /> <AllCrews stateHandler={this.stateHandler}/> <CrewsListFooter navProps={{...this.props}}/> </SafeAreaView> ); } }
额外说明
- 你在父组件里绑定
stateHandler的方式是正确的,this.stateHandler = this.stateHandler.bind(this)确保了函数内部的this指向父组件实例,这样调用setState不会出错。 - 如果后续使用函数式组件的频率较高,建议熟悉React Hooks的写法,比如用
useState来管理状态,代码会更简洁灵活。
内容的提问来源于stack exchange,提问作者F. K.
相关产品推荐
相关产品推荐

