reactjs - Redux:状态只在一个地方更新
问题描述
我是 redux 的新手,我正在尝试通过调查组件中的道具更新状态。
在我的 console.log 中,reducer 中的状态正在更新,但我的应用程序状态保持不变。
在我的 Router.js 中
const intialState = {
currentQuestionId: 1,
}
function reducer(state = intialState, action) {
console.log('reducer', state, action)
switch (action.type) {
case 'INCREMENT':
return {
currentQuestionId: state.currentQuestionId + 1,
}
case 'DECREMENT':
return {
currentQuestionId: state.currentQuestionId - 1,
}
default:
return state
}
}
const store = createStore(reducer)
const Router = () => (
<BrowserRouter>
<Switch>
<Provider store={store}>
<Route path="/survey/:surveyName" component={CNA} />
<Route component={NotFound} />
</Provider>
</Switch>
</BrowserRouter>
)
在 Survey.js 中
class Survey extends Component {
constructor(props) {
super(props)
this.state = {
currentQuestionId: 1,
}
}
previousQuestion = () => {
this.props.decrement()
}
nextQuestion = () => {
this.props.increment()
}
render() {
const { currentQuestionId } = this.state
const { questions } = this.props
return (
<SurveyContainer>
{console.log('surveyState', currentQuestionId)}
<Question
data={questions.find(q => q.id === currentQuestionId)}
/>
<ButtonContainer>
{currentQuestionId > 1 && (
<Button type="button" onClick={this.previousQuestion}>
Previous
</Button>
)}
<Button type="button" onClick={this.nextQuestion}>
Next
</Button>
</ButtonContainer>
</SurveyContainer>
)
}
}
const mapDispatchToProps = {
increment,
decrement,
}
function mapStateToProps(state) {
return {
currentQuestionId: state.currentQuestionId,
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Survey)
我的控制台.log
reducer {currentQuestionId: 5} {type: "INCREMENT"}
SurveyState 1
所以看起来我的减速器实际上正在改变状态,但是,我的调查组件似乎并没有意识到这些变化。
解决方案
推荐阅读
- c++ - 在递归 DP 中,通过存储变量来分解递归调用:效率低下?
- c++ - MFC 编辑控制消息句柄访问 Document 对象
- python - 'c' 参数看起来像单个数字 RGB 或 RGBA 序列
- spring-boot - flyway 从 4.X 升级到 5.x 再次运行已经运行的迁移脚本
- reactjs - 在不刷新页面的情况下反应路由
- c# - 在 RH 上角使用“X”时,应用程序未在调试模式下关闭
- php - 如何将一篇文章发布到多种文章类型?
- python - 在python中查找某些时间范围内的时间重叠
- puppeteer - 使用 xvfb 可以达到的最大分辨率是多少?
- windows - Gammu - gammu - 在windows下检测?