无法使用 useState React 将道具设置为状态

Can't set props to state using useState React

我是新手。我已经阅读了反应文档。我不知道为什么它不起作用。所以,我上来了。

我正在尝试在 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>
  );

并且该注册数组由 TableBody 组件接收。 TableBody 组件中的问题是我无法使用 useState 挂钩将 props 值设置为 state。

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.

我怎样才能把它弄好? 谢谢。

您需要添加一个 useEffect 以在 props 更改时更新 state

来自 useState 文档:

During subsequent re-renders, the first value returned by useState will always be the most recent state after applying updates.

const TableBody = (props) => {
   const { items: passedItems } = props;

   // items is set to `passedItems` only on first render
   // subsequent renders will still retain the initial value in state
   // until `setItems` is called
   const [items, setItems] = useState(passedItems);
   
   // add a `useEffect` to update the state when props change
   useEffect(() => {
     setItems(items)
   }, [items])

   // 
}

我希望它以当前形式工作:

const { items: passedItems } = props;
console.log(passedItems); // ok -> I got what I passed.

const [items, setItems] = useState([]);
console.log(items); // not ok -> items is previously passed items.
useEffect(() => {
  setItems(passedItems)
}, [passedItems])

虽然使用 useState 钩子你应该明白为什么我们需要 useEffect,所以在基于 class 的组件中你有权使用 this.setState 中的回调函数,这将为你提供当前更新的值

this.setState(() => {
  name: 'john'
}, () => console.log(this.state.name)) // you will get the immediate updated value

所以当你谈到功能组件时

const [name, setName] = useState(props.name)
console.log(name) // won't get the updated value

为了获得更新的值,您可以使用 React.useEffect 钩子,当第二个参数发生变化时,它会在数组依赖时触发。

useEffect(() => {
 // logic based on the new value
}, [name]) // so whenever the name value changes it will update and call this useEffect

useEffect可以通过三种方式调用

第一个

不传递 deps 数组

useEffect(() => {}) // this will call everytime

第二个

传递空数组

 useEffect(() => {}, []) // passing empty array,it will call one time like the componentDidMount of class based component

第三个

传递数组 deps(依赖项)

 useEffect(() => {

} , [name, count]) // whenever there is an update of name and count value it will call this useEffect

所以在你的情况下你可以做下面的事情

useEffect(() => {
  setItems(passedItems)
}, [passedItems]) // whenever passedItems changes this will call and setItems will set the new passedItems

希望你对此有清楚的认识。