Hte*_*ing 5 javascript reactjs react-hooks use-effect use-state
我是新来的反应。我已经阅读了 React 文档。我不知道为什么它不起作用。所以,我来到这里。
我正在尝试在反应中创建分页。下面是我的table组件。
const Table = (props) => {
const { description, itemCount, tableHeaders, items } = props;
const pageSize = 5;
const [currentPage, setCurrentPage] = useState(1);
function handlePageChange(page) {
setCurrentPage(page);
}
const registerations = paginate(items, currentPage, pageSize);
// HERE: registerations data is correct and then I pass it to TableBody component.
return (
<React.Fragment>
<TableDescription description={description} count={itemCount} />
<div className="bg-white block w-full md:table">
<TableHeader items={tableHeaders} />
<TableBody items={registerations} />
</div>
{/* Footer & Pagination */}
<div className="bg-white block flex px-6 py-4 justify-between rounded-bl-lg rounded-br-lg">
<div className="sm:flex-1 sm:flex sm:items-center sm:justify-between">
<Pagination
itemsCount={items.length}
pageSize={pageSize}
currentPage={currentPage}
onPageChange={handlePageChange}
/>
</div>
</div>
{/* end Footer & Pagination */}
</React.Fragment>
);
Run Code Online (Sandbox Code Playgroud)
并且该注册数组由 TableBody 组件接收。TableBody 组件中的问题是我无法使用 useState 钩子将道具值设置为状态。
const { items: passedItems } = props;
console.log(passedItems); // ok -> I got what I passed.
const [items, setItems] = useState(passedItems);
console.log(items); // not ok -> items is previously passed items.
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到正确?谢谢你。
在使用 useState 挂钩时,您应该理解为什么我们需要 useEffect,因此在基于类的组件中,您有权使用 this.setState 中的回调函数,这将为您提供当前更新的值
this.setState(() => {
name: 'john'
}, () => console.log(this.state.name)) // you will get the immediate updated value
Run Code Online (Sandbox Code Playgroud)
所以当你谈到功能组件时
const [name, setName] = useState(props.name)
console.log(name) // won't get the updated value
Run Code Online (Sandbox Code Playgroud)
要获取更新的值,您可以使用React.useEffect钩子,只要第二个参数的数组 deps 发生更改,该钩子就会触发。
useEffect(() => {
// logic based on the new value
}, [name]) // so whenever the name value changes it will update and call this useEffect
Run Code Online (Sandbox Code Playgroud)
useEffect 可以通过三种方式调用
第一
不传递 deps 数组
useEffect(() => {}) // this will call everytime
Run Code Online (Sandbox Code Playgroud)
第二个
传递空数组
useEffect(() => {}, []) // passing empty array,it will call one time like the componentDidMount of class based component
Run Code Online (Sandbox Code Playgroud)
第三个
传递数组 deps(依赖项)
useEffect(() => {
} , [name, count]) // whenever there is an update of name and count value it will call this useEffect
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下你可以这样做
useEffect(() => {
setItems(passedItems)
}, [passedItems]) // whenever passedItems changes this will call and setItems will set the new passedItems
Run Code Online (Sandbox Code Playgroud)
我希望你对此有清晰的认识。
| 归档时间: |
|
| 查看次数: |
1969 次 |
| 最近记录: |