[英]React Native - this.setState is not a function
this.setState
不是函数。
export const Router = TabNavigator({
ColorPicker: { screen: ColorPicker },
Palette: { screen: Palette }
});
assignScreenType = screenType => {
this.setState({
currentScreen: screenType
});
};
class App extends Component {
render() {
return (
<Router
screenProps={
{ state, updateRed, updateGreen, updateBlue, updateCyan, updateMagenta, updateYellow, updateBlack, calculateCMYK, calculateRGB, convertToHex, assignScreenType, renderSlider, saveColorSelection }
}
/>
);
}
}
export default App;
<Button
title="Test 1"
onPress={ () => console.log((this.props.screenProps.assignScreenType))}
/>
<Button
title="Test 2"
onPress={ () => this.props.screenProps.assignScreenType('HEXScreen') }
/>
class App extends Component
下方,并在render () {}
上方。 这缓解了this.setState is not a function
但随后引入了一个新的错误: ReferenceError: assignScreenType is not defined
。 class App extends Component
之下以及render () {}
之上时,我尝试使用关键字this
在代码的screenProps部分中传递assignScreenType
,例如: ...this.assignScreenType
我收到了...this.assignScreenType
的新错误this2.props.screenProps.assignScreenType
不是函数,因为该方法现在未定义。 render() {}
并将该方法定义为常量。 这消除了所有错误,但是现在实际上没有任何动作。 constructor
super();
句法。 class App extends Component
之上,然后在Colors.js中调用该函数时,删除匿名函数包装() =>
到目前为止,我尝试过的任何操作都会导致以下错误之一: this.setState is not a function
this.props.screenProps.assignScreenType is not a function
-不执行任何操作。
我已经在这里呆了几个小时了,我没有运气。 我尝试了几种解决方案,曾尝试询问其他开发人员,也曾尝试询问Discord中的React Native社区。 仅使用React时传递props / state / ethods我没有问题,但是尝试通过React Navigation传递props / state / method对我来说不起作用。
你应该定义该方法的类,以便它会有正确this
背景下,然后参考该方法在你的render
与方法this.assignScreenType
:
class App extends Component {
assignScreenType = screenType => {
this.setState({
currentScreen: screenType
});
};
render() {
return (
<Router
screenProps={
{ assignScreenType: this.assignScreenType, /* ...your other screenProps */ }
}
/>
);
}
}
以下将无法正常工作,因为箭头功能根本没有上下文(aka this
):
assignScreenType = screenType => {
this.setState({
因此,使其成为常规函数:
function assignScreenType( screenType) {
this.setState({
然后执行以下操作:
this.props.screenProps.assignScreenType('HEXScreen')
这在调用上下文为screenProps
的函数时都screenProps
,您需要在screenProps
更改上下文:
this.props.screenProps.assignScreenType.call(this, 'HEXScreen')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.