这没有在 setTimeout 中绑定(bind),我在其中调用 setState 函数,为什么会发生这种情况?
我在下面添加了codepen,我在js中尝试了相同的代码,并且它有效
<html>
<head>
<title></title>
<meta charset="UTF-8" />
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@16.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script type="text/babel">
const state = {
eventCount: 0,
}
function setState(newState) {
Object.assign(state, newState);
render();
}
setTimeout(
function() {
this.setState({eventCount: 666});
}
.bind(this),
1000
);
function App() {
return (
<div>
<p>
There have been {state.eventCount} events.
</p>
</div>
)
}
function render() {
ReactDOM.render(<App/>, document.getElementById('root'));
}
render();
</script>
</body>
</html>
https://codepen.io/anon/pen/gZgQWX?editors=1011 ( react ) https://codepen.io/anon/pen/oJZerP?editors=1111 (js 示例)
最佳答案
功能组件没有状态(至少在即将推出的钩子(Hook)功能之前)。没有 setState 方法供您调用。在当前的 React 中,如果你想使用状态,你需要使用类组件,而不是函数组件。
关于javascript - 如何在react功能组件中绑定(bind)? .bind(this) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53886576/