触发mapStateToProps后组件未刷新

时间:2019-05-24 06:41:38

标签: reactjs redux next.js

单击该组件可将您的问题答案保存并重新渲染以显示选定的答案。至少这是目标。

将触发该操作,将数据传递给reducer,并最终使用更新后的数据触发mapStateToProps。所有这些都可以,但是不会重新渲染组件。

我的配置非常简单,过去一直在使用。我一直很小心,不要更改状态并仔细检查变量名,但组件仍不会重新呈现。

动作

  // SAVE ANSWERS 
  export function saveAnswer(answer, questionNum) {
    return (dispatch, getState) => {
      const { answers } = Object.assign({}, getState());
      let newAnswers = answers
      newAnswers[questionNum] = answer

      dispatch({ 
        type: actionTypes.SAVE_ANSWER,
        answers: newAnswers
    })
    }
  }

减速器

export const reducer = (state = initialState, action) => {
    let newState = Object.assign({}, state);
    switch (action.type) {

        case actionTypes.SAVE_ANSWER:
            newState.answers = action.answers
            return newState

        default:
        return state
  }
}

组件连接

...
//Connect Redux
const mapStateToProps = (state) => {
    console.log('mapped', state)
    return {
      settings: state.settings,
      answers: state.answers
    }
  }
  const mapDispatchToProps = { saveAnswer }

  const connectedQuestion = connect(mapStateToProps, mapDispatchToProps)(Question)

  export default connectedQuestion;

组件头

class Question extends React.Component{

    constructor( props ) {
        super( props );

        this.clickedAnswer = this.clickedAnswer.bind( this );
    }

    static async getInitialProps ({query}) {
        return {query}
    }

    render() {
        console.log('rendered', this.props.answers)
        const {settings, query} = this.props
        const currentNumber = parseInt(query.number)
        const currentAnswer = this.props.answers[currentNumber]

        const question = settings.questions[currentNumber - 1] || {}
...

新编辑

我在mapStateToProps函数中添加了一行以强制重新渲染。它有效(但显然非常错误),并证明Redux connect看不到所做的更改。

const mapStateToProps = (state) => {
    return {
      settings: state.settings,
      answers: state.answers,
      rand: Math.random()
    }
  }

尽管当我在此功能中记录状态时,答案显然从[][{Answer}]

0 个答案:

没有答案