【发布时间】:2021-06-17 18:52:28
【问题描述】:
我基本上是在制作一个模仿 Craigslist 的 React 应用程序。登录的用户可以查看作为销售或服务项目的组件。
用户可以点击组件来获取详细信息,这也会呈现一个评论表单。提交表单时,Sale 对象属性“cmets”被更新。但由于引用没有更新,useEffect() 不会触发重新渲染。新评论显示时手动刷新。
我知道我可能需要使用 .map() 创建一个新引用并将状态分配给新引用,但未能成功地将其正确化。
钩子返回一个像这样的对象(里面有'cmets'对象数组):
{
"sale": {
"itemName": "Legos",
"itemInfo": "Dont step on them!",
"price": 33,
"postedBy": testUser,
"likedBy": null,
"createdAt": "2021-06-15T13:20:16.508Z",
"comments": [
{
"commentText": "How many?",
"postedBy": "davey",
"createdAt": "2021-06-17T16:52:55.926Z",
"id": 39
},
{
"commentText": "Could you come down on price?!",
"postedBy": "testUser2",
"createdAt": "2021-06-17T17:14:48.155Z",
"id": 40
}
]
}
}
这是我调用 useEffect() 的代码:
function SalesDetail() {
const { id } = useParams();
const currentUser = useContext(UserContext);
const route = 'sales'
const [sale, setSale] = useState()
useEffect(function getSaleById() {
async function getSale(){
let sale = (await BoonelistApi.getSale(id))
setSale(sale)
}
getSale();
}, [id]);
我尝试让 sale.cmets 成为钩子中的依赖项,但我似乎仍然无法理解它和“不要改变状态”的格言。我也在 Stack 上查看过类似的问题,但无法让它为我工作。
非常感谢任何帮助,如果需要更多详细信息,请告诉我。
【问题讨论】:
-
当有新评论时,组件中
idconst 的值是否会改变? -
the Sale object property 'comments' is updated. But since the reference is not updated, useEffect() does not trigger a re-render.你能说明你是如何更新 cmets 的吗? -
id 取自参数,以提供对数据库中销售项目的引用,作为 sales_id。每个 sales_comment 也有自己的唯一 ID。
标签: javascript reactjs react-hooks use-effect use-state