我正在尝试使用Redux设置React Navigation v3。在react navigation文档中,我可以成功设置导航,并且无需添加redux即可正常运行。但是,当我尝试添加redux class App extends React.Component{...}
并挂接操作时,会引发以下错误:
不变违反:不变违反:在“ Connect(AuthScreen)”的上下文中找不到“ store”。可以将根组件包装在中,也可以在连接选项中将自定义React上下文提供程序传递给Connect(AuthScreen),并将相应的React上下文使用者传递给Connect(AuthScreen)。
App.js
const MainNavigator = createBottomTabNavigator({
welcome: { screen: WelcomeScreen },
auth: { screen: AuthScreen },
main: {
screen: createBottomTabNavigator({
map: { screen: MapScreen },
deck: { screen: DeckScreen },
review: {
screen: createStackNavigator({
review: { screen: ReviewScreen },
settings: { screen: SettingsScreen }
})
}
})
}
});
const AppContainer = createAppContainer(MainNavigator);
class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
);
}
}
export default AppContainer;
这是我要将Redux连接到的AuthScreen:
class AuthScreen extends Component {
componentDidMount(){
console.log('This is this.props in AuthScreen:')
console.log(this.props);
this.props.facebookLogin();
}
render(){
return(
<View>
<Text>AuthScreen</Text>
</View>
)
}
}
export default connect(null, actions)(AuthScreen);
我怀疑我不允许像这样将<Provider>
标签包裹在应用程序容器中,有人可以对如何完成此操作提供一些见解吗?
答案 0 :(得分:3)
因此,我将发布我所拥有的内容,希望对您有所帮助。我有一个单独的文件(AppNavigation.js),可以处理我的应用程序的所有导航。在此AppNavigation上,我有以下内容:
const RootNavigator = createStackNavigator({
<Code here>
})
我的RootNavigator在AppContainer中
const AppContainer = createAppContainer(RootNavigator)
然后,在我的课堂上,我渲染AppContainer。
class AppNavigation extends Component {
constructor(props) {
super(props);
}
render() {
return <AppContainer screenProps={this.props} />
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AppNavigation);
然后,在App.js上,将商店“连接”到RootNavigator
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<RootNavigator />
</Provider>
)
}
}
长话短说:您应该将MainNavigator包装在Provider标签上。
编辑:
const rootReducer = combineReducers({
reducer1,
reducer2,
reducer3...,
})
export default createStore(
rootReducer,
undefined,
applyMiddleware(...middleware)
)
因此,使用这些化简器,您可以通过mapStateToProps将它们“连接”到组件,并在其上使用化简器的状态。
答案 1 :(得分:2)
这是一个简单的示例,可帮助您开始使用React Navigation 3.x和Redux:
App.js
import React, {Component} from 'react';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import Reducers from './src/Reducers';
import Preload from './src/screens/Preload';
let store = createStore(Reducers);
const AppNavigator = createStackNavigator({
Preload: {
screen: Preload,
},
});
const AppContainer = createAppContainer(AppNavigator);
export default class App extends Component {
render () {
return (
<Provider store={store}>
<AppContainer/>
</Provider>
)
}
}