【发布时间】:2020-06-26 13:36:39
【问题描述】:
我正在尝试执行以下操作的 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 无法重新渲染子组件?如果是后者,排序后如何强制重新渲染?
有什么建议吗?谢谢!
【问题讨论】:
标签: javascript reactjs sorting react-hooks