【问题标题】:Can't set props to state using useState React无法使用 useState React 将道具设置为状态
【发布时间】:2023-04-05 12:34:01
【问题描述】:

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

我正在尝试在反应中创建分页。下面是我的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.

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

【问题讨论】:

  • 为什么需要将它们保持在状态中?这就是 state 的行为方式——不是在每次渲染时都重新初始化
  • 因为我需要跟踪哪些注册打开了 view-more btn。在我的 UI 中,我在每次注册时都有查看更多按钮。因此,如果我单击其中一个按钮,我会使用 setItems() 将 { popupVisivility = true } 设置到该注册对象中。然后重新渲染表格并显示弹出窗口。是否有其他方法或其他正确方法来获得该成就?

标签: javascript reactjs react-hooks use-effect use-state


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在使用 useState 钩子时,您应该了解我们为什么需要 useEffect,因此在基于类的组件中,您有权在 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 挂钩,只要数组 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
    

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

    【讨论】:

    • 非常感谢 Thomas 解释了我需要的各个方面。我将继续深入研究这些钩子。
    • 欢迎 Htet,很高兴为您提供帮助 :)
    【解决方案3】:

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

    来自useState 文档:

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2023-03-15
      • 1970-01-01
      • 2020-07-08
      • 2019-10-17
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多