如何在 App.js (React-Native) 中访问 redux 状态
Posted
技术标签:
【中文标题】如何在 App.js (React-Native) 中访问 redux 状态【英文标题】:How to access redux state in App.js (React-Native) 【发布时间】:2020-10-07 07:25:36 【问题描述】:我是 react native 和 redux 的初学者,并且是第一次使用它。我不确定如何在 App.js 文件中使用 store.getState() 中的返回值。
console.ignoredYellowBox = ["Remote debugger"];
import YellowBox from "react-native";
YellowBox.ignoreWarnings([
"Unrecognized WebSocket connection option(s) `agent`, `perMessageDeflate`, `pfx`, `key`, `passphrase`, `cert`, `ca`, `ciphers`, `rejectUnauthorized`. Did you mean to put these under `headers`?",
]);
import React, Component from "react";
import StyleSheet, Text, View, AsyncStorage from "react-native";
import * as Font from "expo-font";
import AppLoading from "expo";
import AppNavigation from "./navigation/AppNavigator";
import setNavigator from "./navigationRef";
import userReducer from "./reducers/userReducer";
import chatReducer from "./reducers/chatReducer";
import Provider from "react-redux";
import createStore, applyMiddleware, combineReducers from "redux";
import ReduxThunk from 'redux-thunk';
import createSocketIoMiddleware from "redux-socket.io";
import io from "socket.io-client";
const store = createStore(combineReducers(userReducer, chatReducer), applyMiddleware(ReduxThunk));
class App extends Component
constructor(props)
super(props);
console.log(props);
this.state =
fontLoaded: false,
;
async componentWillMount()
const response = await(store.getState().userReducer.token)
console.log("Response:", response)
render()
const fetchFont = () =>
return Font.loadAsync(
"raleway-bold": require("./assets/fonts/Raleway-Bold.ttf"),
ralewayBold: require("./assets/fonts/Raleway-Bold.ttf"),
"roboto-regular": require("./assets/fonts/Roboto-Regular.ttf"),
robotoRegular: require("./assets/fonts/Roboto-Regular.ttf"),
Roboto_medium: require("./assets/fonts/Roboto-Regular.ttf"),
);
;
if (!this.state.fontLoaded)
return (
<AppLoading
startAsync=fetchFont
onFinish=() => this.setState( fontLoaded: true )
onError=(err) =>
console.log(err);
/>
);
return (
<Provider store=store>
<AppNavigation
ref=(navigator) =>
setNavigator(navigator);
/>
</Provider>
);
const styles = StyleSheet.create(
container:
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
,
);
export default App;
我想从这里访问 redux 状态以访问存储在那里的令牌。在参考了几篇文章后,我尝试使用 store.getState() 方法,但是当我 console.log 它时,我得到了 null
【问题讨论】:
【参考方案1】:您不应直接使用对store
的引用,而应使用connect
方法连接您的组件,在本例中为App
到商店,如下所示:
import connect from 'react-redux';
...
class App extends Component
constructor(props)
console.log(props.token);//you will get here the token
...
...
....
const mapStateToProps = (state) =>
return
token: state.userReducer.token,
;
;
const mapDispatchToProps = (dispatch) =>
return //You should put here your dispatch methods later
;
;
export default connect(mapStateToProps, mapDispatchToProps)(App)
---------------已编辑-----------
我刚刚注意到您正在尝试访问 App 组件中的 store
,但是由于您在 App.render
方法中定义了提供程序,因此您应该做以下两件事之一:
1)您应该在App上方添加<Provider store=store>
。在索引中。
<Provider store=store>
<App />
</Provider>
在这种情况下,App 渲染不应再包含 Provider。
2) 你应该将使用令牌的逻辑移到App
以下的级别,并在下面的组件上使用连接:
class IntermediateComponent extends Component
constructor(props)
console.log(props.token);//you will get here the token
...
const mapStateToProps = (state) =>
return
token: state.userReducer.token,
;
;
const mapDispatchToProps = (dispatch) =>
return //You should put here your dispatch methods later
;
;
const ConnectedIntermediateComponent = connect(mapStateToProps, mapDispatchToProps)(IntermediateComponent)
class App extends Component
...
render()
<Provider store=store>
<ConnectedIntermediateComponent>
<AppNavigation
ref=(navigator) =>
setNavigator(navigator);
/>
</ConnectedIntermediateComponent>
</Provider>
export default App;
请注意,在 2) App 中不再连接。
【讨论】:
感谢您的回答,但是当我在 App.js 文件中使用 connect 时,出现此错误。 " 在 "Connect(App)" 的上下文中找不到 "store"。要么将根组件包装在简介
App.js 调用的示例代码
<Provider store=store>
<App />
</Provider>
现在我们将尝试在没有 react-redux 的 connect 的情况下从 store dispatch 和 getState p>
通过这种方法,我们将不再需要 mapStateToProps 和 mapDispatchToProps
因为我们已经在 App.js 中导入我们的 store。例如
import store from "./redux/store";
首先,我们直接通过 store 从 App.js 调度一些操作。
就像我们在我们的 epic 文件夹中有这样的动作
import someAction from './redux/epics/fetch-some-epic'
现在这是来自 App.js
的 dispatch 操作 store.dispatch(someAction())
这是我们可以从 App.js
中的 store 获得的状态store.getState().someState
感谢和问候
别忘了关注
【讨论】:
以上是关于如何在 App.js (React-Native) 中访问 redux 状态的主要内容,如果未能解决你的问题,请参考以下文章
react-native初探——helloworld demo
如何在 react-native 中将函数的结果从一个组件传递到另一个组件?