简体   繁体   English

React 渲染前一个数组 state(排序)

[英]React rendering previous array state (sorting)

Basically im developing a component where i use the.map method in an array stored in a state and render another component for each occurrence of that array, besides that im making a component that sorts the array according to some parameters using the.sort method基本上我正在开发一个组件,我在存储在 state 的数组中使用 .map 方法,并为该数组的每次出现呈现另一个组件,除了我制作一个组件,该组件使用 .sort 方法根据某些参数对数组进行排序

The problem im facing is that my component is rendering the previous state of the array, so if i sort it by a parameter and then sort it by another parameter, the array showing rendered on the screen is the one sorted by the first parameter, just like that:我面临的问题是我的组件正在渲染数组的前一个 state,所以如果我按一个参数对其进行排序,然后按另一个参数对其进行排序,则屏幕上显示的数组是按第一个参数排序的数组,只是像那样:

(likes = sort by highest green number | deslikes = sort by highest red number) (喜欢 = 按最高绿色数字排序 | 不喜欢 = 按最高红色数字排序)

在此处输入图像描述

The code:编码:

  • Component rendering the array组件渲染数组

 export default function Piadas() { const [searchBarContent, setSearchBarContent] = useState(""); const [order, setOrder] = useState(""); const [jokes, setJokes] = useState([]) useEffect(() => { if(jokes.length == 0) fetchData("getJokes"); }, [jokes]) function fetchData(url) { fetch(`http://localhost:3006/${url}`).then(response => { return response.json(); }).then(data => { setJokes(data.data); }); } return ( <div> <Head> <title>Só piada boa</title> <meta name="description" content="Aplicação utilizando Banco de dados, CRUD, REST e Next.JS" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <ContainerStageBackgroundPiadas> <LightBrownMobileWrapper> <UtilsWrapper searchBarContent={searchBarContent} setSearchBarContent={setSearchBarContent} order={order} setOrder={setOrder} jokes={jokes} setJokes={setJokes} /> <CardWrapper> { jokes.map((data) => ( <Card data={data} key={uuidv4()} /> )) } </CardWrapper> </LightBrownMobileWrapper> </ContainerStageBackgroundPiadas> </main> </div> ); }

  • Popover component that orders onChange of the input:对输入进行 onChange 排序的 Popover 组件:

     export default function Popover({order, setOrder, jokes, setJokes}) { useEffect(() => { if(order === "likes") setJokes(jokes.sort((a, b) => (a.likes < b.likes? 1: -1))) else if(order === "dislikes") setJokes(jokes.sort((a, b) => (a.dislikes < b.dislikes? 1: -1))) console.log(jokes); }, [order, jokes, setJokes]) return ( <PopoverContainer style={{width: "100%"}}> <PopoverTrigger> Ordenar </PopoverTrigger> <PopoverContent> <div> <input type="radio" name="orderRadio" value="likes" onChange={(event) => setOrder(event.target.value)} /> <p>Likes</p> </div> <div> <input type="radio" name="orderRadio" value="dislikes" onChange={(event) => setOrder(event.target.value)} /> <p>Deslikes</p> </div> </PopoverContent> </PopoverContainer> )

    } }

I solved the problem by changing the way i was doing the sort, i was changing the state directly and then doing the map on that state, now that state remains with his original value and then i make the.sort directly in his original value on the render, maybe react doenst handle well the first way (sorting the value of the state i was mapping), anyway this looks way better now: I solved the problem by changing the way i was doing the sort, i was changing the state directly and then doing the map on that state, now that state remains with his original value and then i make the.sort directly in his original value on渲染,也许第一种方式反应很好(对我正在映射的 state 的值进行排序),无论如何现在看起来好多了:

 function sortParams(a, b){ if(order === "likes"){ return a.likes < b.likes? 1: -1 } else if(order === "dislikes") return a.dislikes < b.dislikes? 1: -1 } return ( <div> <Head> <title>Só piada boa</title> <meta name="description" content="Aplicação utilizando Banco de dados, CRUD, REST e Next.JS" /> <link rel="icon" href="/favicon.ico" /> </Head> <main> <ContainerStageBackgroundPiadas> <LightBrownMobileWrapper> <UtilsWrapper searchBarContent={searchBarContent} setSearchBarContent={setSearchBarContent} order={order} setOrder={setOrder} /> <CardWrapper> { jokes.sort(sortParams).filter(filterParams).map((data) => ( <Card data={data} key={uuidv4()} /> )) } </CardWrapper> </LightBrownMobileWrapper> </ContainerStageBackgroundPiadas> </main> </div> ); }

you should remember that sort modify the original values so you could simply get a copy of the jokes by either [...jokes] or jokes.slice()您应该记住sort会修改原始值,这样您就可以通过[...jokes]jokes.slice()简单地获取jokes的副本

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

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