首页 > 解决方案 > 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

所以看起来我的减速器实际上正在改变状态,但是,我的调查组件似乎并没有意识到这些变化。

标签: reactjsoopecmascript-6reduxreact-redux

解决方案


推荐阅读