reflux / refluxjs

A simple library for uni-directional dataflow application architecture with React extensions inspired by Flux
BSD 3-Clause "New" or "Revised" License
5.36k stars 330 forks source link

State management question in Reflux.Store and Reflux.Component #513

Closed LiangZugeng closed 7 years ago

LiangZugeng commented 7 years ago

Since states can be declared in both Store and Component, and according to my test, I was unable to correctly setState in Component to a state declared in Store, for example:

`class Store extends Reflux.Store { constructor() { super(); this.state = { data: [1,2,3] }; } ... }

class PageA extends Reflux.Component { constructor(props) { super(props); this.state = {}; }

componentDidMount() { this.setState({ data: [1,2] }); // this won't work as data was declared in Store, turns out the data remains the same after this line of code. } ... }`

So my question is: is there any guideline for the state management? which type of state should be maintained and managed by Store, and which should go into Component?

Plus I can only find document saying the state in Store will be mixed into Component, but it's lack of information on how those state in Store is mixed and if they can be manipulated in Component or vice versa.

BryanGrezeszak commented 7 years ago

That's because that would go against the entire concept of what flux is :) Components don't directly change a store's state, they dispatch actions which a store then uses to change its state. That's how the 1 way data flow works in flux concepts. actions --> stores --> components --> actions again...

Any state in the store is maintained by that store via the actions it receives.

If you want state that's just a normal part of your component, Reflux does not stop that. It only augments and adds state from stores, it doesn't change your ability to use component state normally like you would in any other component (except for possible name conflicts, of course).

constructor(props)
{
    super(props);
    this.store = MyStore; // <-- has a state prop `foo1`
    this.state = {foo2: 'bar2'};
}

componentDidMount()
{
    this.setState({foo2:'another val'}); //  works like normal to set local state
    MyActions.doSomething(); // an action that may change foo1 in the store
}