我的 redux 状态改变了,但视图没有

时间:2021-05-03 12:24:12

标签: redux react-redux

我正在开发一款名为“你愿意”的游戏, 游戏允许用户从用户名中选择作为假登录,

我的游戏一切正常 但是当用户回答问题时,状态会发生变化,但视图不会重新呈现 我认为这是因为突变,但我找不到我的错误,所以这是我的代码

questions.js 减速器

        case ADD_ANSWER:
            const {qid,answer,authedUser} = action.payload
            return {
                ...state,
                [qid]:{
                    ...state[qid],
                    [answer]:{
                        ...state[qid][answer],
                        votes:[...state[qid][answer].votes, authedUser]
                    }
                }
            }

users.js 减速器

        case ADD_USER_ANSWER:
            const {qid,authedUser,answer} = action.payload
            return{
                ...state,
                [authedUser]:{
                    ...state[authedUser],
                    answers:{
                    ...state[authedUser].answers,
                    [qid]:answer
                },
              },
            }

我使用 redux-thunk 在一个函数中调用这两个操作

shared.js

export const handleAddAnswer = ({authedUser,qid,answer})=>{
    return (dispatch)=>{
                _saveQuestionAnswer ({ authedUser, qid, answer }).then(()=>{
                    dispatch(addAnswer({authedUser,qid,answer}))
                    dispatch(addUserAnswer({authedUser,qid,answer}))
        })
    }

}

然后最后我使用 mapStateToProps 在我的组件中使用它 Home.js 组件

function mapStateToProps({questions,authedUser,users}){
    return {
        questions,
        unanswered:Object.values(questions).filter((question)=>{
            if(!Object.keys(authedUser.answers).includes(question.id)){
                return question
            }
        }).sort((a,b)=>b.timestamp - a.timestamp),
        answered:Object.values(questions).filter((question)=>{
            if(Object.keys(authedUser.answers).includes(question.id)){
                return question
            }
        }).sort((a,b)=>b.timestamp - a.timestamp),
        users,
        authedUser,
    }
}
export default connect(mapStateToProps)(Home)

0 个答案:

没有答案