Reactjs 为什么我的组件在使用map后没有更新?
我在数据结构中使用了一个映射,但是当我的数据更新时,组件不会更新。为什么会这样 我使用Reactjs 为什么我的组件在使用map后没有更新?,reactjs,redux,Reactjs,Redux,我在数据结构中使用了一个映射,但是当我的数据更新时,组件不会更新。为什么会这样 我使用console.log输出5条数据,但是页面上只有3条数据,不会更新 组成部分 在中使用“只读”修饰符 只读状态={value:''} 这意味着无法重新分配“状态”您的articleReduce正在修改现有状态值注释,而不是以不变的方式创建副本: export-const-articleducer=createReducer,这是官方推荐的编写redux(并且与TypeScript配合得很好)的方法。如果您有
console.log
输出5条数据,但是页面上只有3条数据,不会更新
组成部分
在中使用“只读”修饰符 只读状态={value:''}
这意味着无法重新分配“状态”您的articleReduce正在修改现有状态值
注释
,而不是以不变的方式创建副本:
export-const-articleducer=createReducer,这是官方推荐的编写redux(并且与TypeScript配合得很好)的方法。如果您有一个代码段可以清楚地显示您的问题,请提供一个工作代码段,与没有代码段的情况下相比,它可以更快地解决您的问题。您应该从删除诸如redux state(使其成为一个数组)之类的值开始。然后就不用更新了。Map可以快速查询所需的数据,如果使用数组,查询会变得非常麻烦@HMR@jack程序员忽视他们使用的库的作者的建议比在数组中查找项更麻烦。非常感谢您的建议。我将使用immutable
尝试重写数据结构@HMRREADOLY是一个类型脚本修饰符,对运行时JavaScript没有任何影响。此外,本地组件状态似乎在这个问题中没有任何作用。几乎等于:tsx构造函数(props:props){super(props);this.state={value:''}}
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);
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>;
import {createAction} from "typesafe-actions";
export const submitComment = createAction("SUBMIT_COMMENT", (title: string) => (title))();