请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

redux 报了警告 Can't call setState on a component that is not yet mounted

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都是目前最新的版本

正在回答 回答被采纳积分+3

1回答

Dell 2020-07-25 18:22:52

Store.subscribe(this.handleStoreChange); 写在 componentDidMount 里面

9 回复 有任何疑惑可以回复我~
  • 这样写确实没有报错了, 为什么老师再讲解过程中 不是这样写的,却没有遇到这样的问题? 还是说插件更新了,有更规范的写法了, 学习比较晚,问题多,老师见谅
    回复 有任何疑惑可以回复我~ 2021-12-30 10:36:52
  • 是的,应该是因为新版本里的实现略有改版
    回复 有任何疑惑可以回复我~ 2022-01-02 19:06:26
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号