操作正在更新状态,但mapStateToProps中的道具在Component中显示为未定义



我正在编写一个简单的多项选择题评估应用程序,它可以让你点击一个答案,然后将其突出显示并添加到答案数组中。如果用户已经单击了答案数组中的其他选项,则会从中删除这些选项。动作被正确调度,但我在组件中使用的道具显示为未定义。我肯定我已经把这件事弄得太复杂了(我是个初学者(,所以任何帮助都很感激。我看了大约7篇其他SO帖子,但设置不同,它们在mapStateToProps和mapDispatchToProps中不包括多个项目(不确定这是否有区别。(

question.reducer.js

const INITIAL_STATE=
{
answers:[],
i:1,
j:2,
k:3,
l:4,
i_Checked:"",
j_Checked:"",
k_Checked:"",
l_Checked:""
};
const questionReducer=(state=INITIAL_STATE,action)=>{
switch(action.type){
case QuestionActionTypes.CLICK_I:
return{
...state,
answers: changeI(state.i,state.j,state.k,state.l,state.answers),
i_Checked:"checked",
j_Checked:"",
k_Checked:"",
l_Checked:""
};

reducer中的"changeI"是我的utils.js文件夹中的一个util函数,它为正确的div赋予className"checked",如果不包括它,则将其添加到answers数组中,同时从answers阵列中删除其他多选选项。这一切都很好。是mapStateToProps中的道具让我抓狂!

有问题的组件

import React from 'react';
import './multiple-choice.styles.scss';
import {connect} from 'react-redux';
import {i_Clicked,j_Clicked,k_Clicked,l_Clicked} from '../../redux/question/question.actions';
const MultipleChoice= ({i_Checked,j_Checked, k_Checked, l_Checked, i_Clicked,j_Clicked,k_Clicked,l_Clicked,i,j,k,l})=>{
let answerUrl="../../../public/images/answer";
let formVisible="none";
let mcVisible="";

return(
<div  style={{display: mcVisible}}>
<div className='row'>
//answer choice 1
<div onClick={i_Clicked} className={`${i_Checked} column`} >
<img alt="Possible Answer" src={`${answerUrl}${i}.png`}/>
</div>
//answer choice 2
<div onClick={j_Clicked} className={`${j_Checked} column`}>
<img alt="Possible Answer" src={`${answerUrl}${j}.png`}/>
</div>
</div>
<div className="row">
//answer choice 3
<div onClick={k_Clicked} className={`${k_Checked} column`}>
<img alt="Possible Answer" src={`${answerUrl}${k}.png`}/>
</div>
//asnwer choice 4
<div  onClick={l_Clicked} className={`${l_Checked} column`}>
<img alt="Possible Answer" src={`${answerUrl}${l}.png`}/>
</div>
</div>
</div>
)
}
const mapDispatchToProps=dispatch=>({
i_Clicked: ()=> dispatch(i_Clicked()),
j_Clicked: ()=> dispatch(j_Clicked()),
k_Clicked: ()=> dispatch(k_Clicked()),
l_Clicked: ()=> dispatch(l_Clicked())
});
const mapStateToProps=state=>({
i_Checked: state.i_Checked,
j_Checked:state.j_Checked,
k_Checked:state.k_Checked,
l_Checked:state.l_Checked,
i:state.i,
j:state.j,
k:state.k,
l:state.l
});
export default connect(mapStateToProps,mapDispatchToProps)(MultipleChoice);

当我点击问题的第一个答案(用字母"I"表示I,j,k,l(时,它会出现在答案数组中,I_checked的值为"checked",所以这个操作似乎有效,只是道具没有加载到组件中?

你能发布你的root reducer文件吗?。你使用combineReducers的地方

export default combineReducers({
question: QuestionReducer,
});

如果这就是您实现mapStateToProps的方式,则应按照以下进行更改

const mapStateToProps=state=>({
i_Checked: state.question.i_Checked,
j_Checked:state.question.j_Checked,
k_Checked:state.question.k_Checked,
l_Checked:state.question.l_Checked,
i:state.question.i,
j:state.question.j,
k:state.question.k,
l:state.question.l
});

状态将包括整个冗余存储和与问题部分相关的question填充参考数据

相关内容

  • 没有找到相关文章

最新更新