状态更新后,我将无法呈现数据。
但是提交后我会在控制台上获取数据
我正在使用ContextApi
数据
<div>
{datas.map(data => {
return (
<button
key={data.id}
onClick={() => handleData(data)}
className="btn btn-primary m-4"
>
{data.title}
</button>
);
})}
<DetailData />
</div>
特定数据的详细信息 **其中包含一个输入框,用户可以在其中输入评论,评论将显示在上方
**
return (
<>
{DetailData == null ? (
<></>
) : (
<div className="card mx-4">
<div className="card-body">
<h5 className="card-title">{DetailData.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">
Id: {DetailData.id}
</h6>
<p className="card-text">{DetailData.Description}</p>
</div>
<hr />
comment:{DetailData.comment}
<CommentBox bid={DetailData.id} cm={DetailData.comment} />
</div>
)}
</>
);
答案 0 :(得分:1)
在您的ContextApi中进行此更改,找到“添加以下行注释”: 通过另一种方式,您需要在提交后更新DetailData
import React, { Component, createContext } from "react";
export const Contx = createContext();
export class ConProvider extends Component {
state = {
name: "",
datas: [
{
id: 1,
title: "Reactjs",
Description:
"React is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications, as it is optimal for fetching rapidly changing data that needs to be recorded.",
comment: []
},
{
id: 2,
title: "Bootstrap",
Description:
"Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. It contains CSS- and JavaScript-based design templates for typography, forms, buttons, navigation and other interface components",
comment: []
}
],
DetailData: null
};
handleData = data => {
this.setState({
DetailData: data
});
};
handleInput = e => {
this.setState({
[e.target.name]: e.target.value
});
};
handleSubmit = async commentid => {
const com = this.state.name;
const updateComment = await this.state.datas.map(c => {
if (c.id === commentid) {
return {
...c,
comment: [...c.comment, com]
};
} else {
return c;
}
});
// Added this line
const dData = await updateComment.filter(c => c.id === commentid);
this.setState({
datas: updateComment,
name: "",
DetailData: dData[0] // Added this line
});
};
render() {
return (
<Contx.Provider
value={{
...this.state,
handleData: this.handleData,
handleInput: this.handleInput,
handleSubmit: this.handleSubmit
}}
>
{this.props.children}
</Contx.Provider>
);
}
}