Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - React-Redux: Should all component states be kept in Redux Store

Say I have a simple toggle:

When I click the button, the Color component changes between red and blue

I might achieve this result by doing something like this.

index.js

Button: onClick={()=>{dispatch(changeColor())}}
Color: this.props.color ? blue : red

container.js

connect(mapStateToProps)(indexPage)

action_creator.js

function changeColor(){
 return {type: 'CHANGE_COLOR'}
}

reducer.js

switch(){
case 'CHANGE_COLOR':
return {color: true}

but this is a hell of a lot of code to write for something that I could have achieved in 5 seconds with jQuery, some classes, and some css...

So I guess what I'm really asking is, what am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Redux is primarily intended for "application state." That is, anything related to your application logic. The view built on top of it is a reflection of that state, but does not have to exclusively use that state container for everything it does.

Simply ask these questions: Is this state important to the rest of the application? Will other parts of the application behave differently based on that state? In many minor cases, that will not be the case. Take a drop down menu: The fact that it's open or closed probably won't have an effect on other parts of the app. So, wiring it up to your store is probably overkill. It's certainly a valid option, but doesn't really net you any benefits. You're better off using this.state and calling it a day.

In your particular example, does the color that button is toggled to make any difference in other parts of the application? If it's some sort of global on/off toggle for a major part of your application, it definitely belongs in the store. But if you're just toggling a button color when you click the button, you can leave the color state locally-defined. The action of clicking the button might have other effects that require an action dispatch, but that is separate from the simple question of what color it should be.

In general, try to keep your application state as small as possible. You don't have to shove everything in there. Do it when you have to or it makes a lot of sense to keep something there. Or if it makes your life easier when using Dev Tools. But don't overload its importance too much.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...