我想建立一个单页登录系统,根据我在React Redux存储中设置的状态呈现不同的页面。当商店的状态更新时,render() {}
函数不更新。
App.js
import React from 'react'
import store from './redux/store'
import { Provider } from 'react-redux'
// Route to Renderer.js below
import Renderer from './Renderer'
class App extends React.Component {
render() {
return (
<Provider store={ store }>
<Renderer page={store.getState().page} />
</Provider>
)
}
}
export default App;
Renderer.js
import React, { Component } from 'react'
// Routes to my pages I plan to render
import Login from './routes/Login'
import About from './routes/About'
import Register from './routes/Register'
class Renderer extends Component {
render() {
let page = this.props.page
let returned
switch (page) {
case 'About':
returned = <About />
break
case 'Login':
returned = <Login />
break
case 'Register':
returned = <Register />
break
default:
returned = <About />
}
return returned
}
}
export default Renderer
我有一个链接到Redux Action的组件,它更改了page
字段的状态。为了简单起见,没有显示这一点。状态的变化得到了确认,因为Redux开发工具告诉我,当我调度操作以更改page
Redux状态时,状态发生了变化。当我更改page
字段的Redux状态时,呈现的页面不会更新,而是停留在默认页面。
不要将page
作为隐式道具传递给Renderer
,而是使用react-redux
连接,以便使用mapStateToProps
函数将此道具传递给组件:
Renderer.js
import React, { Component } from 'react'
import {connect} from 'react-redux'
// Routes to my pages I plan to render
import Login from './routes/Login'
import About from './routes/About'
import Register from './routes/Register'
class Renderer extends Component {
render() {
let page = this.props.page
let returned
switch (page) {
case 'About':
returned = <About />
break
case 'Login':
returned = <Login />
break
case 'Register':
returned = <Register />
break
default:
returned = <About />
}
return returned
}
}
const mapStateToProps = (state)=>({
page: state.page
})
export default connect(mapStateToProps)(Renderer)
App.js
import React from 'react'
import store from './redux/store'
import { Provider } from 'react-redux'
// Route to Renderer.js below
import Renderer from './Renderer'
class App extends React.Component {
render() {
return (
<Provider store={ store }>
// remove the page prop here
<Renderer />
</Provider>
)
}
}
export default App;
通过这样传递页面道具:page={store.getState().page}
您的Renderer
组件实际上并没有订阅存储更改,因此它将始终返回初始的page
值。
react-redux
connect
包装器负责对存储的订阅,因此您的组件将在每次存储更新时从Provider
获得更新的页面值。