【问题标题】:Get values from map function without rerendering too many useState React从 map 函数中获取值而无需重新渲染太多 useState React
【发布时间】:2022-11-21 04:30:17
【问题描述】:

我在从地图函数返回值时遇到问题。当我从 useState 设置状态时,它会重新呈现。

const [getPrice, setPrice] = useState([]);

    recordProcedures.map((item) => (
        item.chosen != null ?
        item.chosen.map((proc) =>(
            console.log('Inner Map:',proc),
            console.log('Procedure:',proc.procedure),
            console.log('Price:',proc.price)
        ))
        : null
    ))

这就是 console.log 的样子 console.log preview

现在,如果我设置这样的状态

const [getPrice, setPrice] = useState([]);

    recordProcedures.map((item) => (
        item.chosen != null ?
        item.chosen.map((proc) =>(
            console.log('Inner Map:',proc),
            console.log('Procedure:',proc.procedure),
            console.log('Price:',proc.price)
           setPrice(proc.price)
        ))
        : null
    ))

它渲染多次并出现错误console.log(getPrice) 如何在不重新渲染使用的情况下返回/获取地图函数内的值

【问题讨论】:

  • 将问题分为两半,1.使用 array.filter 过滤所选数组,2.使用 array.find 在第一步返回的所选数组中找到您想要的项目,最后设置它的价格

标签: reactjs


【解决方案1】:

钩子只能在函数组件的内部调用。 您不能直接调用 setState。而是使用useEffect

  useEffect(()=>{
     const price = recordProcedures?.map((item) => (
        item.chosen?.map((proc) =>proc.price)
    ))
    setPrice(price)
  }, [])

【讨论】:

    猜你喜欢
    • 2020-08-15
    • 1970-01-01
    • 2021-10-21
    • 2020-11-27
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多