Reactjs 存储更改时,组件未正确更新 我正在开发一个react应用程序,当触发post按钮时,数据没有正确显示,插入了一个新行,但是与这些相关联的数据没有显示在正确的索引中。 |这里| 232|
现在,HERE字符串位于索引232,在我触发按钮后,它只是向store数组添加了一个元素,我在233处看到HERE字符串,这是不正确的,因为HERE应该保留其索引 我尝试了一些不同的方法:purecomponents,将数据从存储区复制到组件状态 {this.props.chapters.mapchapter,索引=>{ 回来 }} 桌椅 从React导入React,{Component,Fragment}; 类TableRow扩展组件{ 状态={ 标题: }; 静态GetDerivedStateFromPropsExtProps,prevState{ 返回{ 标题:nextrops.chapter.title, id:nextrops.chapter.id }; } 渲染{ 回来 { this.setState{…this.state,title:e.target.value}; }} /> {this.state.id} {this.props.exposure} ; } } 导出默认表行; 减速机,但POST_章工作正常,数组调度正确,问题是ReactReactjs 存储更改时,组件未正确更新 我正在开发一个react应用程序,当触发post按钮时,数据没有正确显示,插入了一个新行,但是与这些相关联的数据没有显示在正确的索引中。 |这里| 232|,reactjs,react-redux,Reactjs,React Redux,现在,HERE字符串位于索引232,在我触发按钮后,它只是向store数组添加了一个元素,我在233处看到HERE字符串,这是不正确的,因为HERE应该保留其索引 我尝试了一些不同的方法:purecomponents,将数据从存储区复制到组件状态 {this.props.chapters.mapchapter,索引=>{ 回来 }} 桌椅 从React导入React,{Component,Fragment}; 类TableRow扩展组件{ 状态={ 标题: }; 静态GetDerivedStat
import {
FETCH_ALL_CHAPTER,
POST_CHAPTER,
PUT_CHAPTER,
DELETE_CHAPTER
} from "../actions/ChapterActions";
const INITIAL_STATE = {
chapter_list: []
};
export default function chapterReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_ALL_CHAPTER:
return { ...state, chapter_list: [...action.payload] };
case DELETE_CHAPTER:
let chaptersCopy0 = state.chapter_list.filter(
s => s.uuid !== action.payload
);
return {
...state,
chapter_list: [...chaptersCopy0]
};
case POST_CHAPTER:
return {
...state,
chapter_list: [
...action.payload,
...state.chapter_list
]
};
case PUT_CHAPTER:
let indexToSub = state.chapter_list.findIndex(
s => s.uuid === action.payload.uuid
);
let chaptersCopy1 = [...state.chapter_list];
chaptersCopy1[indexToSub] = action.payload;
return {
...state,
chapter_list: [...chaptersCopy1]
};
default:
return state;
}
}
行动:
export function postChapter(customer_uuid, assessment_uuid, chapter_data) {
let url = `${ROOT_URL}/x/${customer_uuid}/assessmentcontainers/${assessment_uuid}/chapters/`;
return dispatch => {
return axios
.post(url, chapter_data)
.then(res => {
dispatch({
type: POST_CHAPTER,
payload: res.data
});
dispatch(
notifSend({
message: "Created",
kind: "success",
dismissAfter: 2000
})
);
return res;
})
.catch(error => {
console.log(error);
if (error !== UNAUTHORIZED_ERROR)
dispatch(
notifSend({
message: messageStatus(error),
kind: "danger",
dismissAfter: 2000
})
);
return { status: error.status };
});
};
}
您将在数组的开头插入新的章节,这将更改以下所有元素的索引
{
...state,
chapter_list: [
...action.payload,
...state.chapter_list
]
};
你能把你的代码放在codesandbox上吗?你为什么使用PureComponent?这里是什么?你的reducer代码在哪里?对不起,编辑好了。关于PureComponent,我只是试图强制react重新渲染。现在是一个组件。非常感谢。是的,我需要的是:顶部的新章节。我还尝试从后端重新获取整个列表,但这并没有影响bug的持续存在。@FrancescoMagarotto这不是bug-JavaScript数组就是这样工作的。如果您有一个数组[a,b,c],然后在开头添加一个项,因此您有[d,a,b,c],那么“c”的索引已从2更改为3。你也许应该使用章节ID作为你的键。我创建了一个数组,使用uuid作为索引。非常感谢