繁体   English   中英

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

[英]Can't set props to state using useState 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.

我怎样才能使它正确? 谢谢你。

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

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 中使用回调 function ,这将为您提供当前更新的值

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钩子,只要数组 deps 作为第二个参数发生更改,就会触发该钩子。

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

我希望你对此有明确的想法。

props发生变化时,您需要添加一个useEffect来更新state

useState文档:

在后续重新渲染期间,useState 返回的第一个值将始终是应用更新后的最新 state。

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])

   // 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM