简体   繁体   中英

React + Redux - architectural approach

Hi Stackoverflow'ers :)

I'm currently learning React+Redux. I have an architectural question I hope you can answer.

Lets assume I have an interface where I can create questions and save them to an API. Initially the currently saved questions are loaded from the API and saved in the Redux store.

The answers array could look something like this:

 var answers = [ { id: 1, title: 'can crop circles be square?', correct: false }, { id: 2, title: 'can you daydream at night?', correct: true } { id: 3, title: 'do Jewish vampires still avoid crosses?', correct: true }, ] 

In my interface I have different options for editing or delete a given question. Therefore I want to set an active state on the question I'm editing. A way to do it is to change the Redux state, so each question have an active property. If I'm editing question 1, the state would look like this:

 var answers = [ { id: 1, title: 'can crop circles be square?', correct: false, active: true }, { id: 2, title: 'can you daydream at night?', correct: true } { id: 3, title: 'do Jewish vampires still avoid crosses?', correct: true }, ] 

My concern is that I'm mixing my apps state together with the API data. Is this the correct way to do it, or is there a better way to separate API data from state?

I think you just need to centre your understanding of data scope on the web-app as it is defined by the redux state-tree, remembering that the state-tree is the complete definition of your app.

Thinking of things this way clears up the problem. Now there is no such thing as "API data", there is simply initial-state that has been sourced from somewhere. Perhaps from local-storage, perhaps from an API across the machine-boundary, it doesn't matter as it is just data that has been used to initialise a branch of the state-tree. Once that branch has been initialised, and the data absorbed into the body of the state, then you are free to make arbitrary changes according to the demands of the app.

Only one argument can be made against this - what if the data needs to be returned to the original source? As the data leaves the app and, in the case of an API, crosses the machine boundary, it will need to be recast into the correct shape. There is nothing unusual here, and the requirement to do this should not unnecessarily inform the shape of the state-tree.

In short, don't worry about "apps state together with the API data". Fill the state-tree with data and structure it precisely as the app demands. Extract the data as external requirements demand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM