Javascript React Native-this.setState不是函数 使用的技术: 自然反应 问题:
Javascript React Native-this.setState不是函数 使用的技术: 自然反应 问题:,javascript,reactjs,react-native,mobile,react-navigation,Javascript,Reactjs,React Native,Mobile,React Navigation,此.setState不是一个函数 代码: 路由器.js App.js assignScreenType=screenType=>{ 这是我的国家({ 当前屏幕:屏幕类型 }); }; 类应用程序扩展组件{ render(){ 返回( ); } } 导出默认应用程序; Colors.js console.log((this.props.screenProps.assignScreenType))) /> this.props.screenProps.assignScreenType('HEXSc
此.setState
不是一个函数
代码:
路由器.js
App.js
assignScreenType=screenType=>{
这是我的国家({
当前屏幕:屏幕类型
});
};
类应用程序扩展组件{
render(){
返回(
);
}
}
导出默认应用程序;
Colors.js
console.log((this.props.screenProps.assignScreenType)))
/>
this.props.screenProps.assignScreenType('HEXScreen')}
/>
console.log显示的内容:
我所尝试的:
- 我已经将我的方法移到
和类应用程序扩展组件下方
上方。这减轻了渲染(){}
This.setState不是函数的问题,但随后引入了一个新错误:
ReferenceError:assignScreenType未定义
- 当该方法位于下面的
和上面的class App extends Component
时,我尝试使用关键字render(){}
在代码的screenProps部分传递this
,像这样:assignScreenType
我得到一个新的错误…this.assignScreenType
不是一个函数,因为该方法现在未定义this2.props.screenProps.assignScreenType
- 我已将我的方法移动到
下,并将该方法定义为常量。这消除了所有错误,但现在实际上没有任何操作发生render(){}
- 我尝试过使用
构造函数
super()代码>语法
- 我尝试过使用curry方法,并将其放在
之上,然后在Colors.js中调用函数时,删除匿名函数包装class App extends Component
()=>
- 我已经通过Discord与当地社区取得了联系,但也没有运气
this.setState不是一个函数
-this.props.screenProps.assignScreenType不是一个函数
-没有动作发生
我已经干了好几个小时了,但运气不好。我试过几种解决方案,我试过询问另一位开发人员,我试过询问本地社区的反应。在使用just React时,我没有问题传递道具/状态/方法,但尝试通过React导航传递道具/状态/方法对我不起作用。以下功能不起作用,因为箭头函数根本没有上下文(也称为
此
):
因此,使其成为常规功能:
function assignScreenType( screenType) {
this.setState({
然后执行以下操作:
this.props.screenProps.assignScreenType('HEXScreen')
当它调用上下文为screenProps
的函数时,它也不起作用,您需要在那里更改上下文:
this.props.screenProps.assignScreenType.call(this, 'HEXScreen')
您应该在类上定义方法,使其具有正确的
this
上下文,然后使用this引用render
方法中的方法。assignScreenType
:
class App extends Component {
assignScreenType = screenType => {
this.setState({
currentScreen: screenType
});
};
render() {
return (
<Router
screenProps={
{ assignScreenType: this.assignScreenType, /* ...your other screenProps */ }
}
/>
);
}
}
类应用程序扩展组件{
assignScreenType=屏幕类型=>{
这是我的国家({
当前屏幕:屏幕类型
});
};
render(){
返回(
);
}
}
OP希望this
引用组件实例,因此它确实需要是类方法,或者在本例中是类上的函数属性。您的解决方案有效。我最初在类上定义了所有方法。然而,你的解决方案中我从未想到的部分是:当你特别键入:{assignScreenType:this.assignScreenType}
——我只是刚刚将assignScreenType
传递给屏幕道具。每当我尝试放置this.assignScreenType
时,我都会得到一个错误,即this
是一个保留字。我甚至没有想过使用对象密钥/对。你是我的英雄。非常感谢我接受了你的回答。祝你过得愉快,伙计!键/值对*
function assignScreenType( screenType) {
this.setState({
this.props.screenProps.assignScreenType('HEXScreen')
this.props.screenProps.assignScreenType.call(this, 'HEXScreen')
class App extends Component {
assignScreenType = screenType => {
this.setState({
currentScreen: screenType
});
};
render() {
return (
<Router
screenProps={
{ assignScreenType: this.assignScreenType, /* ...your other screenProps */ }
}
/>
);
}
}