我有一个带有删除按钮的Comment组件。单击该按钮时,它将调用操作,进行axios调用,并在调用返回时将更新分派到reducer。唯一的问题是,它不会触发父组件的重新渲染。该动作尽管正在更新状态,但不会出现在Redux DevTools中的已调度动作列表中。所有其他操作都可以在DevTools中运行并显示,但是由于某种原因,该操作不起作用。
阅读下面的评论部分后,我的想法是,这是因为我正在对对象进行浅表复制。我认为制作浅表副本,修改更深的对象并返回浅表副本不会触发重新渲染,我是否认为错误?浅对象是否足以触发它的引用不是事实吗?我相信我在其他地方也可以这样做,而且在其他地方也没有问题。它
这是Redux DevTools中删除注释后的操作列表。我希望它在底部某处附近有“ delete_comment”,但事实并非如此:
数据从父组件CommentList-> CommentThread-> Comment传递。
这是真正的调度吗?
这是一个简化的组件:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {
deleteComment,
} from "../../actions/comment_actions";
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
const {comment, data} = this.props;
if (!data) {
//console.log("mir_data doesnt exist");
return <div/>;
}
return (
<div key={"comment" + comment.id} id={"c" + comment.id}>
<button onClick={() => this.props.deleteComment(comment.id)}>Delete</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.user
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
deleteComment,
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Comment);
这是一个简化的操作文件:
export const DELETE_COMMENT = 'delete_comment';
export function deleteComment(id, callback = null) {
return (dispatch, getState) => {
axiosInstance.post('/delete-comment/', {comment_id: id}, getState().api.axios).then(
response => {
dispatch(dispatchDeleteComment(id));
//dispatch(dispatchViewUserInfo(response.data));
if (response.status === 200)
callback();
}
);
}
}
export function dispatchDeleteComment(id) {
return {
type: DELETE_COMMENT,
payload: id
};
}
这是简化的减速器:
import {DELETE_COMMENT} from "../actions/comment_actions";
export default function(state = {}, action){
let newState = {...state};
switch(action.type){
case DELETE_COMMENT:
//some logic
delete newState.comments[action.payload];
return newState;
default:
return state;
}
}