React Render Map最后一个元素不会更新

时间:2016-12-13 08:48:27

标签: javascript reactjs

映射中的最后一个FileComponent不反映状态更改,它事件不会调用shouldComponentUpdate。更改其他FileComponents(但最后)后,除最后一个之外的所有FileComponents都反映了更改,并且每次调用shouldComponentUpdate。

在render方法的React组件中,我使用:

{this.props.files.map((file,index)=>{
    return (
        <FileComponent type="upload" key={index} index={index} />
    )
})}

在FileComponent中,我有带onClick功能的按钮:

this.props.dispatch({type: "EDIT_FILE", payload: this.props.index});
    // SOME STRANGE BEHAVIOUR
    // if(this.props.index+1 == this.props.files.length){
    //     this.forceUpdate();
    // }

我的减速机包含:

function getInitialState(){
   return {
    files:  [
        {name: 'asd.doc', in_edit: false,
            file: {type:'image/png', size:123123, lastModifiedDate:new Date()}
        },
        {name: '22.doc', in_edit: false,
            file: {type:'image/png', size:123123, lastModifiedDate:new Date()}
        },
        {name: 'as33d.doc', in_edit: false,
            file: {type:'image/png', size:123123, lastModifiedDate:new Date()}
        },
        {name: '44.doc', in_edit: false,
        file: {type:'image/png', size:123123, lastModifiedDate:new Date()}
        },
    ]
}
}

export default function (state = getInitialState(), action) {
switch (action.type) {

 case "EDIT_FILE":
        state.files[action.payload]['in_edit'] = !state.files[action.payload]['in_edit'];
        return Object.assign({}, state);
default:
        return state
}
}

的package.json:

"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-dropzone": "^3.7.3",
"react-redux": "^4.4.5",
"react-router": "^3.0.0",
"react-router-redux": "^4.0.7",
"redux": "^3.6.0",

它是否应该理解我的问题?

1 个答案:

答案 0 :(得分:0)

解决方案是更改reducer代码以参考文件操作,而不是整个状态:

case "EDIT_FILE":
        let files = state.files.slice(0);
        files[action.payload]['in_edit'] = !files[action.payload]['in_edit'];

        return Object.assign({}, state, {files:files});