我正在尝试执行以下操作的 react/react 钩子编写代码。
从父组件获取一组对象作为 prop 使用useState
钩子将其设置为状态。根据预期的过滤器(时间和评级)对状态进行排序,并重新渲染子组件。我看到的是,下面的代码在排序后更新了状态,但是即使状态更新了,依赖于该状态的子组件也不会重新渲染。我认为子组件会在状态改变时自动重新渲染?
import React, {useState} from 'react';
import ProfilePostspreview from './ProfilePostspreview';
function ProfileNavigation(props){
const [newarray, setnewarray]=useState(props.parray); //'parray' object passed as props and saved as 'newarray' state
const otc = () => { //Function to sort the state by time and set a new state
let k=newarray;
setnewarray(k.sort((a, b) => (a.time > b.time) ? -1 : 1 ));
}
const orc = () => { //Function to sort the state by rating and then time and set a new state
let k=newarray;
setnewarray(k.sort((a, b) => (a.rating > b.rating) ? -1 : (a.rating === b.rating) ? ((a.time > b.time) ? -1 : 1) : 1 ));
}
return (
<div>
<div className="sm_options"> //Component to trigger the otc and orc functions
<div className="sm_button" id="order_t" onClick={otc}>Sort by time</div>
<div className="sm_button" id="order_r" onClick={orc}>Sort by rating</div>
</div>
<div className="posts_preview_columns_p"> //This is dependent on the 'newarray' state but is not re-rendering even after the state is sorted and updated?
{newarray.map(na=>
<ProfilePostspreview
postThumbnail={na.photolink}
rating={na.rating}
time={na.time}
target={na.target}
/>
)}
</div>
</div>
);
}
export default ProfileNavigation;
这可能是什么原因?代码是否有问题,或者对状态进行排序是否被认为不足以让 React 重新渲染子组件?如果是后者,如何在排序后强制重新渲染?
有什么建议吗?谢谢!