I mine componentWillMount()is called every time I switch routes.
Is there any other way to handle storage state changes?
When I use two functions for the first time, this is normal, but when I switch routes and go back and try to use them again, I get this message
warning.js:45 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
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;
}
addItem( title, stockQuantity ) {
const id = Date.now();
this.items.push({
id,
title,
stockQuantity
});
this.emit("change");
}
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;
source
share