javascript - this.setState() 似乎不能采用非立即函数
问题描述
我有一个反应类:
class App extends React.Component{
// Make a constructor to hold attributes in memory.
constructor(props){
// This line is needed to instantiate
super(props)
// Attributes when this object is init for first time.
this.state = {
count:0
}
}
render(){
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.count}>Count!</button>
</div>
);
}
// Set the count attribute to point to some nameless function.
count = () => {
// a built in method to update state of an object.
// setState takes a state and does the following.
this.setState(state => ({
count:state.count + 1
})
)
}
}
this.setState 正确地采用了匿名函数。但是,当我尝试像这样传递一个非匿名函数时,我得到一个错误:ReferenceError: Can't find variable: state rethrowCaughtError — react-dom.development.js:321:
count = () => {
// a built in method to update state of an object.
// setState takes a state and does the following.
function some_func(state){
count:state.count + 1
}
this.setState(some_func(state))
}
为什么会这样?
解决方案
首先,您在函数中调用 plus 时传递了state
in some_function
,但您没有返回任何内容。试试这个:
count = () => {
// a built in method to update state of an object.
// setState takes a state and does the following.
function some_func(state){
return {...state, count: state.count + 1}
}
this.setState(some_func(this.state))
};
推荐阅读
- arrays - REACT 如何在 setState 中存储对象而不是对象数组?
- wordpress - iframe 链接部分首先显示在 wordpress 网站的页面加载中
- android - 如何在 android 中显示动画标记谷歌地图?
- mysql - 无法连接到数据库 sonarqube
- laravel - 使用 auth Laravel 时如何删除 url 中的 /login
- search - Showing error in Search Command Power Apps
- php - woocommerce_thankyou。如何将变量(来自插件)放入其中
- postgresql - postgresql 查询和数据库性能调优
- bash - Shell脚本:在检索带有转义序列的变量值时,转义序列字符的行为如何?
- list - 在 OCaml 中列出过滤器然后列出地图