我是新来的反应js.我正在创建用户输入和要输入的实际句子之间的比较不知何故我能够实现这一点但它不完美,就像嵌套地图无法正确呈现如果字母输入正确它应该呈现绿色背景我的状态是正确更新但我的嵌套地图金达不工作有一个延迟
组件代码
renderLine = () => { let test = this.props.test.get('master') return test.map(line => { return line.check.map( (ltr,i) => ltr.status ? <span key={i} className="correct">{ltr.letter}</span> : ltr.letter ) }) }; handleKeyPress = e => { if(e.charCode === 32) { this.setState({ pushToNext:true,currentTyping:"" }) } }; handleInput = e => { if(e.target.value !== " "){ let {storeValue} = this.state; console.log(storeValue.length); let updatedWord = e.target.value; let updateArr = []; if(storeValue.length === 0){ updateArr = storeValue.concat(updatedWord) }else { if(this.state.pushToNext){ updateArr = storeValue.concat(updatedWord) }else { storeValue.pop(); updateArr = storeValue.concat(updatedWord); } } this.setState({ currentTyping:updatedWord,storeValue:updateArr,pushToNext:false },() => { let {storeValue} = this.state let lastWordIndex = storeValue.length === 0 ? storeValue.length : storeValue.length - 1; let lastLetterIndex = storeValue[lastWordIndex].length === 0 ? storeValue[lastWordIndex].length : storeValue[lastWordIndex].length - 1; let lastWordValue = storeValue[lastWordIndex]; let lastLetterValue = lastWordValue[lastLetterIndex]; // console.log(lastWordIndex,lastLetterIndex,lastWordValue,lastLetterValue,"After tstae") return this.props.compareCurrentTextWithMater(lastWordIndex,lastLetterValue) }); } };
Redux减速机
import {FETCH_USER_TYPING_TEXT,COMPARE_TEXT_WITH_MASTER} from "../actions/types"; import {fromJS} from 'immutable'; const initialState = fromJS({ text:null,master:[],inputBoxStatus:false }); export default function (state = initialState,action) { switch (action.type){ case FETCH_USER_TYPING_TEXT: return setTextManipulated(state,action); case COMPARE_TEXT_WITH_MASTER: return compareTextWithMaster(state,action) default: return state } } const compareTextWithMaster = (state,action) => { let {lastWordIndex,lastLetterValue} = action; let masterWord = state.get('master')[lastWordIndex]; let masterLetter = masterWord.check[lastLetterIndex]; let newState = state.get('master'); if(typeof masterLetter !== "undefined"){ if(masterLetter.letter === lastLetterValue){ masterWord.check[lastLetterIndex].status = true; newState[lastWordIndex] = masterWord; return state.set('master',newState) }else { masterWord.check[lastLetterIndex].status = false; newState[lastWordIndex] = masterWord; return state.set('master',newState) } }else { console.log('Undefinedd Set Eroing or wrong Space Chratced set Box Red Colot',newState); } };
UPDATE
我使用普通的React.js做了同样的逻辑它完美地工作并且嵌套地图正确渲染了if else逻辑没有信函延迟
https://codesandbox.io/s/zx3jkxk8o4
但是与Redux State使用不可变js的相同逻辑如果使用else语句我不知道问题依赖于什么,而且我的代码片段与CodeSanBox COde略有不同但是逻辑是相同的