【问题标题】:React and Redux: How do I get the value of my application's state/Redux store at any point in my app?React 和 Redux:如何在我的应用程序中的任何时候获取应用程序的状态/Redux 存储的价值?
【发布时间】:2017-01-06 11:29:31
【问题描述】:

我有一个 reactjs 网络应用程序。我想向服务器发出请求并希望包含应用程序的整个状态。我如何实现这一目标?

【问题讨论】:

  • 您为什么要根据请求将整个应用程序状态发送到服务?虽然这是可能的,但这不是好的做法。
  • 我们希望在某些有缺陷的情况下跟踪应用程序的状态,以便我们可以更好地调试
  • 我假设您想要生产快照?在开发中,您可以使用其他工具,例如 logger 或 devtools。另一种选择是使用存储侦听器,然后将其存储在一个变量中以供您的 fetch 调用使用。
  • 我发现这个 npm 模块叫做 redux bug 报告器:npmjs.com/package/redux-bug-reporter。它解决了我的问题,因为它在发送请求时捕获了状态。我对此进行了调整并完成了我的任务。

标签: reactjs redux react-redux


【解决方案1】:

所以基本上你需要在使用状态 (http://redux.js.org/docs/api/createStore.html) 进行任何网络调用之前使用 createstore 库创建整个商店。您可以按照自己的意愿使用组合减速器对树进行分组。 (http://redux.js.org/docs/recipes/reducers/UsingCombineReducers.html)。一个例子是

export default combineReducers({
  stateVariable1 : Reducer1,
  stateVariable2 : Reducer2...
});

每个 reducer 都应被视为您要分组的状态的一部分。 (http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html)

然后在应用程序的任何组件中,您都可以使用连接库将其与状态树连接起来,以调度操作、获取状态项。您还可以提及您想要访问状态树的哪一部分。

例如

const mapStateToProps = (state) => ({
  Reducer1 : StateVariable1 // Reducer1 in component can be accessed as this.props.Reducer1
});

const mapDispatchToProps = (dispatch) => ({
  quickinvestListingsActions : bindActionCreators(quickinvestListingsActions, dispatch) // Dispatching actions
});

export default connect(mapStateToProps, mapDispatchToProps)(QuickInvestListings); // This connects the component with the redux state

因此您可以将 Reducer1 用于任何目的,包括发送请求

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    相关资源
    最近更新 更多