redux 报了警告 Can't call setState on a component that is not yet mounted
来源:5-5 Action 和 Reducer 的编写
Charles_So_网页开发
2020-07-24
import React from "react";
import Store from "./store.js";
import { CHANGE_NAME } from "./actionTypes";
import { Input } from "antd";
export default class Home extends React.Component {
constructor(props) {
super(props);
Store.subscribe(this.handleStoreChange);
}
state = Store.getState();
onInput = e => {
const value = e.target.value;
Store.dispatch({ type: CHANGE_NAME, value });
};
handleStoreChange = () => {
this.setState(Store.getState());
};
componentWillUnmount() {
console.log("ummount");
}
render() {
return (
<div>
<Input value={this.state.name} onChange={this.onInput} />
</div>
);
}
}
控制台一直报错误:
Warning: Can’t call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state
directly or define a state = {};
class property with the desired state in the Home component.
请问是什么原因?
react和redux都是目前最新的版本
写回答
1回答
-
Dell
2020-07-25
Store.subscribe(this.handleStoreChange); 写在 componentDidMount 里面
922022-01-02