m0_62452255
2022-04-23 23:08
采纳率: 83.3%
浏览 27
已结题

React 在父组件添加按钮怎么对API获得的name字段进行排序?(语言-javascript)

React 父组件添加按钮怎么对name字段进行排序


import React, { useState, useEffect } from 'react'
function Father() {
    //定义State为数组,setState是获得的数据
    const [State, setState] = useState([])//name
    const [count, setCount] = useState([])//username
    const [isName, setIsName] = useState(true)

    useEffect(() => {
        //fetch请求数据
        fetch("https://jsonplaceholder.typicode.com/users")
            .then((res) => res.json())
            .then(data => {
                console.log(data);

                let list = data.map((post) => {
                    return post.name
                    
                });

                let list2 = data.map((post) => {
                    return post.username
                });
                //打印list
                console.log(list)
                console.log(list2)

                //将list赋值给setState
                setState(list)
                setCount(list2)
             //sort排序
                // list.sort(() => {
                //     return (
                //         Math.random() - 0.5);
                //   }); document.write(list);
              
            })
            //使用 catch() 去捕获错误
            .catch(err => console.log(err));
    }, [])

    let xxx = isName ? State : count
    console.log(xxx)
   
    return (
        <div >

            

            {xxx.map(name => { return <Son value={name} key={name} /> })}

            <button onClick={() => { setIsName(!isName) }}>name更换username</button><hr />
            <button onClick={() => {}} >筛选按钮</button >
        </div>)

}
function Son(props) {
    return (
        <div >
            <p>
                子组件:{props.value}
            </p>
        </div>
    )
}

export { Father, Son }



运行结果

img

怎么添加一个效果图,分别展示name,username,email,address信息

(例图如下)

img

1条回答 默认 最新

相关推荐 更多相似问题