简体   繁体   English

如何使用Redux获取另一个组件的本地状态

[英]How to get local state of another component using Redux

Using react + redux, I am making an app where you answer questions, 5 questions per step and about 20 steps. 使用react + redux,我正在制作一个应用程序,您可以在其中回答问题,每步5个问题,大约20个步骤。 When starting a new step, I save the progress to localStorage. 开始新步骤时,我将进度保存到localStorage。 My app structure is like this: 我的应用程序结构如下:

 class App extends Component { render() { return ( <Provider store={store}> <Router> <div id="ocean-model"> <Topbar /> <main id="main"> <Route exact path="/" component={Landing} /> <Switch> <PrivateRoute exact path="/survey" component={Survey} /> </Switch> <Switch> <AdminRoute exact path="/edit-questions" component={EditQuestions} /> <AdminRoute exact path="/add-question" component={AddQuestion} /> </Switch> </main> </div> </Router> </Provider> ); } } 

In Survey component I use controlled inputs to save current answers to local state and on submitting all 5 answers I use redux action to save given answers to localStorage and redux store. 在Survey组件中,我使用受控输入将当前答案保存到本地状态,并在提交所有5个答案时使用redux操作将给定答案保存到localStorage和redux存储中。

In Topbar component I have a button, which onClick I would like to take the current progress from redux store, but also get the currently answered questions(for example 2 out of 5), which are only available in the Survey component's local state. 在Topbar组件中,我有一个按钮,我希望onclick可以从redux商店获取当前进度,但也可以获取当前已回答的问题(例如5分之2),仅在Survey组件的本地状态下可用。

Do I need to modify the App structure so that Topbar and Survey can share state or maybe in Survey I need to somehow listen to an onclick event of a button from Topbar? 我是否需要修改App结构,以便Topbar和Survey可以共享状态,或者在Survey中,我需要以某种方式侦听Topbar中按钮的onclick事件?

Is there any reason you can't save given answer to localStorage and redux store when the input loses focus? 当输入失去焦点时,是否有任何原因无法保存给定的答案到localStorage和redux存储? Might need to allow for the action to fire if the Topbar component button is clicked while the focus is still on the last input with an answer. 如果在焦点仍位于带有答案的最后一个输入上时单击“顶栏”组件按钮,则可能需要触发该操作。

The alternative would be to use React Context as your state container for each set of 5 questions and use that from both the form and the Topbar button with a Provider located in the component tree above both. 替代方法是将React Context用作每个5个问题集的状态容器,并使用表单和Topbar按钮中的问题容器,并在两个树上方的组件树中使用Provider。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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