如何将状态映射到初始文件(App.js或Index.js)上的props?



这可能是非常基本的东西。我的应用程序上有一个微调器,其中声明了路由和提供程序。这必须是读取 redux 存储,特别是 spinner.visible 并映射到状态,以便我可以隐藏/显示<Spinner>元素。

但正如我所说...这是应用程序的入口文件。我知道如何使用connect将其映射到props,但看起来我不能在我的条目文件上使用connect/mapStateToProps。

这很好用,但我不认为使用订阅是最好的方法。我想让微调器能够以优雅的方式直接阅读商店。有什么建议吗?

import React from 'react'
import {Provider} from 'react-redux'
import {View} from 'react-native'
import {createStore, applyMiddleware} from 'redux'
import Spinner from 'react-native-loading-spinner-overlay'
import ReduxThunk from 'redux-thunk'
import reducers from './reducers'
import Routes from './config/routes'
import {getReady} from './services/registration'
import {setAppInitialLoad, setAppSpinner} from './actions/AppActions'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
initialized: false,
spinner: {
visible: false,
text: ''
}
}
store.subscribe(() => {
//ToDo: I really hope to find an elegant solition for this.
//Since it' the top level JS file of the app, I can't use
//connect/mapStateToProps to map the props :(
const spinner = store.getState().AppReducer.spinner
if(spinner.visible != this.state.spinner.visible) {
this.setState({
spinner: {
visible: spinner.visible,
text: spinner.text
}
});
}
}
)
}
componentDidMount() {
store.dispatch(setAppSpinner({ visible: true, text: 'Loading...'}))
getReady().then(response => {
store.dispatch(setAppInitialLoad(response.data.data))
store.dispatch(setAppSpinner({ visible: false, text: ''}))
this.setState({initialized: true})
})
}
render() {
if (this.state.initialized) {
return (
<View>
<Provider store={store}>
<Routes/>
</Provider>
<Spinner visible={this.state.spinner.visible} textContent={this.state.spinner.text}
textStyle={{color: '#000'}}/>
</View>
)
} else {
return (
<View style={{backgroundColor: 'yellow', flex: 1}}/>
)
}
}
}
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk))
export default App;

使用可以使用存储变量 (在您的代码中,它在这里:const store = createStore(reducers, {}, ...)

存储变量有一些方法,你可以在这里阅读(https://redux.js.org/basics/store(

最新更新