javascript – ComponentwillMount被调用两次

每次切换路由时都会调用我的componentWillMount().

还有其他方法可以处理商店状态的变化吗?

当我第一次使用这两个功能时它没问题但是,当我切换路线并返回并尝试再次使用它时,我收到此消息

warning.js:45警告:setState(…):只能更新已安装或安装的组件.这通常意味着您在已卸载的组件上调用了setState().这是一个无操作.请检查未定义组件的代码.

InventoryList.js

import React from "react";
import InventoryItem from "../components/InventoryItem";
import InventoryItemStore from "../stores/InventoryItemStore";
import { Link } from "react-router";

export default class InventoryList extends React.Component {
    constructor() {
        super();
        this.state = {
            items: InventoryItemStore.getAll(),
        }
    }

    componentWillMount() {
        InventoryItemStore.on("change", () => {
            this.setState({
                items: InventoryItemStore.getAll()
            });
        });
    }

    render(...);
}

InventoryStore.js

import { EventEmitter } from "events";

import dispatcher from "../dispatcher";

class InventoryItemStore extends EventEmitter {

    constructor() {
        super()
        this.items = [
            {
                id: 1,
                title: "first item",
                stockQuantity: 10
            },
            {
                id: 2,
                title: "second item",
                stockQuantity: 5
            }
        ];
    }

    getAll() {
        return this.items;
    }

    // Adds new item to the inventory store
    addItem( title, stockQuantity ) {
        const id = Date.now();
        this.items.push({
            id,
            title, // We don't have to do title: title because of ES6... Thx ES6
            stockQuantity
        });

        this.emit("change");
    }


    /**
     * Lower the stock quantity of certain item
     * @param  {integer} id
     * @param  {integer} stockQuantity
     */
    lowerQuantity( id, orderQuantity ) {

        this.items.map((item) => {

            if ( item.id == id ) {
                item.stockQuantity = item.stockQuantity - orderQuantity;
            }

        });

        this.emit("change");

    }


    handleActions( action ) {

        switch( action.type ) {
            case "ADD_ITEM": {
                const { title, stockQuantity } = action;
                this.addItem( title, stockQuantity );
            }
            case "LOWER_QUANTITY": {
                const { id, orderQuantity } = action;
                this.lowerQuantity( id, orderQuantity );
            }
        }

    }

}

const inventoryItemStore = new InventoryItemStore;

dispatcher.register(inventoryItemStore.handleActions.bind(inventoryItemStore));

export default inventoryItemStore;

最佳答案 每次更改路径时都会卸载组件,并在更改后安装新组件.

由于您正在使用InventoryItemStore.on注册一个事件处理程序,但从未取消注册它,因此您将看到两个组件正在侦听更改,而未安装的组件会抛出该错误.

使用componentWillUnmount取消注册您的组件,使其不会像鬼一样徘徊,并在您导航回来时困扰您.

有关更多生命周期挂钩,请参阅React lifecycle.

点赞