React在下拉框选择后不立即更新状态。

huangapple go评论49阅读模式
英文:

React doesnt update state immidiately after dropdown selected

问题

当下拉框被选中时,我有一些更新状态的问题。

当被选中时,useEffect不会立即更新状态。

我希望我的列表数组在选定的筛选条件更改时立即更新。

谢谢

const dropdowns = [
    { icon: '', title: 'Top ratings', color: 'warning' },
    { icon: '', title: 'Worst ratings', color: 'warning' },
]

const [selectedFilter, setSelectedFilter] = useState('')
useEffect(() => {
    if (selectedFilter === 0) {
        var sorted = listings.sort((a, b) => { return b.rating - a.rating })
        setListings(sorted)
        console.log(listings)
    } else {
        var sorted = listings.sort((a, b) => { return a.rating - b.rating })
        setListings(sorted)
        console.log(listings)
    }
}, [selectedFilter])

<Dropdown.Menu className='w-100'>
    {dropdowns.map(({ icon, title }, indx) => (
        <Dropdown.Item
            key={indx}
            as='button'
            eventKey={title}
            onClick={() => {
                setSelectedFilter(indx)
            }}>
            <i className={`${icon} fs-lg opacity-60 me-2`}></i>
            {title}
        </Dropdown.Item>
    ))}
</Dropdown.Menu>

请注意,上述内容是已翻译的代码部分。

英文:

I have some update state problems when the dropdown is selected.

The useEffect doesnt update the state immidiately when its selected.

I want my listngs array updated immidiately whenever the selected filter changes.

Thanks

Code

const dropdowns = [
    { icon: &#39;&#39;, title: &#39;Top ratings&#39;, color: &#39;warning&#39; },
    { icon: &#39;&#39;, title: &#39;Worst ratings&#39;, color: &#39;warning&#39; },
]
  
const [selectedFilter, setSelectedFilter] = useState(&quot;&quot;)
  useEffect(() =&gt; {
    if (selectedFilter === 0) {
      var sorted = listings.sort((a, b) =&gt; { return b.rating - a.rating })
      setListings(sorted)
      console.log(listings)
    } else {
      var sorted = listings.sort((a, b) =&gt; { return a.rating - b.rating })
      setListings(sorted)
      console.log(listings)
    }
  }, [selectedFilter])



&lt;Dropdown.Menu className=&#39;w-100&#39;&gt;
     {dropdowns.map(({ icon, title }, indx) =&gt; (
      &lt;Dropdown.Item
       key={indx}
       as=&#39;button&#39;
       eventKey={title}
       onClick={() =&gt; {
       setSelectedFilter(indx)
       }}&gt;
      &lt;i className={`${icon} fs-lg opacity-60 me-2`}&gt;&lt;/i&gt;
      {title}
      &lt;/Dropdown.Item&gt;
      ))}
  &lt;/Dropdown.Menu&gt;

答案1

得分: 2

你可能会发现阅读“您可能不需要效果”部分很有用,特别是“根据props或state更新状态”部分。

最终,你不需要使用效果来计算派生数据,你应该直接在渲染中进行计算。

const dropdowns = [
    { icon: '', title: 'Top ratings', color: 'warning' },
    { icon: '', title: 'Worst ratings', color: 'warning' },
]

const [selectedFilter, setSelectedFilter] = useState("")

const sortedListings = selectedFilter === 0 ?
  [...listings].sort((a, b) => b.rating - a.rating) : 
  [...listings].sort((a, b) => a.rating - b.rating);

<Dropdown.Menu className='w-100'>
     {dropdowns.map(({ icon, title }, indx) => (
      <Dropdown.Item
       key={indx}
       as='button'
       eventKey={title}
       onClick={() => {
       setSelectedFilter(indx)
       }}>
      <i className={`${icon} fs-lg opacity-60 me-2`}></i>
      {title}
      </Dropdown.Item>
      ))}
  </Dropdown.Menu>

另一个值得注意的事情是,在你的 useEffect 中,你正在改变 listings,这很可能是不可取的;相反,你应该克隆数组,然后进行排序(因此使用 [...listings].sort() 而不是 listings.sort())。

英文:

You probably will find it useful to read through the "You might not need an effect", in particular the "Updating state based on props or state" section.

Ultimately you don't need an effect to compute derived data, you should just do that directly in render.

const dropdowns = [
    { icon: &#39;&#39;, title: &#39;Top ratings&#39;, color: &#39;warning&#39; },
    { icon: &#39;&#39;, title: &#39;Worst ratings&#39;, color: &#39;warning&#39; },
]

const [selectedFilter, setSelectedFilter] = useState(&quot;&quot;)

const sortedListings = selectedFilter === 0 ?
  [...listings].sort((a, b) =&gt; b.rating - a.rating) : 
  [...listings].sort((a, b) =&gt; a.rating - b.rating);

&lt;Dropdown.Menu className=&#39;w-100&#39;&gt;
     {dropdowns.map(({ icon, title }, indx) =&gt; (
      &lt;Dropdown.Item
       key={indx}
       as=&#39;button&#39;
       eventKey={title}
       onClick={() =&gt; {
       setSelectedFilter(indx)
       }}&gt;
      &lt;i className={`${icon} fs-lg opacity-60 me-2`}&gt;&lt;/i&gt;
      {title}
      &lt;/Dropdown.Item&gt;
      ))}
  &lt;/Dropdown.Menu&gt;

The other thing worth noting is in your useEffect you're mutating listings which is most likely not desirable; instead you should clone the array then sort (hence [...listings].sort() rather than listings.sort()).

huangapple
  • 本文由 发表于 2023年2月8日 20:28:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定