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 里面

9
2
Dell
回复
qq_人醉梦未碎_0
是的,应该是因为新版本里的实现略有改版
2022-01-02
共2条回复

React零基础入门到实战,完成企业级项目简书网站开发

主流新技术 React-redux,React-router4,贯穿基础语法

5275 学习 · 2496 问题

查看课程