我在数据结构中使用了映射,但当我的数据更新时,组件不会更新。为什么会这样呢?
我使用console.log输出了5个数据,但是页面上只有3个数据,它们不会被更新!

组件
import React, {ChangeEventHandler, Component} from "react";
import {connect} from 'react-redux';
import {RootState} from "typesafe-actions";
import {getMessage} from "./store/selectors";
import {submitComment} from './store/actions'
const mapDispatchToProps = {
submit: submitComment
};
const mapStateToProps = (state: RootState) => {
return {
article: getMessage(state.article, 1)
}
}
type Props = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps;
type State = {
value: string
}
class Todo extends Component<Props, State> {
readonly state = {value: ''}
public render() {
return (
<div>
<h1>{this.props.article?.title}</h1>
{this.props.article?.comments.map((comment) => <li key={comment.title}>{comment.title}</li>)}
<input type="text" onChange={this.onChange}/>
<button onClick={this.handleSubmit}>submit</button>
</div>
)
}
private handleSubmit = () => {
this.props.submit(this.state.value);
}
private onChange: ChangeEventHandler<HTMLInputElement> = (e) => {
this.setState({value: e.currentTarget.value});
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Todo);reducer.ts
import {createReducer, PayloadAction} from "typesafe-actions";
import * as actions from './actions';
interface Comment {
title: string
}
interface Article {
title: string
comments: Comment[]
}
interface App {
articles: Map<number, Article>
}
const initState: App = {
articles: new Map<number, Article>([
[1, {title: 'article', comments: [{title: 'comment-1'}, {title: 'comment-2'}]}]
])
}
export const articleReducer = createReducer<App>(initState)
.handleAction(actions.submitComment, (state: App, action: PayloadAction<string, string>) => {
const article = state.articles.get(1)
article?.comments.push({title: action.payload})
console.log(article?.comments);
return {
articles: state.articles
}
});
export default articleReducer;
export type ArticleState = ReturnType<typeof articleReducer>;actions.ts
import {createAction} from "typesafe-actions";
export const submitComment = createAction("SUBMIT_COMMENT", (title: string) => (title))();发布于 2020-11-24 02:58:04
您的articleReduce正在修改现有的状态值comments,而不是以不可变的方式创建副本:
export const articleReducer = createReducer<App>(initState)
.handleAction(actions.submitComment, (state: App, action: PayloadAction<string, string>) => {
return {
articles: state.articles.map((article, idx) => idx !== 1 ? article : { ...article, comments: [...article.comments, action.payload] })
}
});如果你想在reducers中使用可变逻辑(如.push),请参阅redux toolkit,这是编写redux的官方推荐(与TypeScript配合非常好)。
发布于 2020-11-24 01:22:48
中使用“readonly”修饰符
只读状态= {value:''}
这意味着'state‘不能被重新赋值
https://stackoverflow.com/questions/64971121
复制相似问题