用于显示初始数据的效果钩子

时间:2020-01-04 12:03:49

标签: reactjs react-hooks fetch-api

我有默认的App函数,该函数在创建时会提供反应。

我正在尝试获取一些数据以进行初始显示:

const [people, setPeople] = useState([]);

useEffect(() => {
        fetch("http://localhost:8080/restApiTest").then(res => {
            return res.json();
        }).then(data => {
            let array_people = data.map((p) => {
                return p.firstName + ' ' + p.lastName;
            });
            setPeople(array_people);
        });
    }, []);

问题在于仅当我重新渲染子组件时才渲染此数据。如何加载初始数据?

我尝试关注React Effect HooksReact State Hooks

编辑:添加其余功能

function App() {
    // const people = ["Arnaud", "Etienne", "Riccardo", "Ed", "Jose"];
    const [people, setPeople] = useState([]);
    const [filtered, setFiltered] = useState(people);

    useEffect(() => {
        fetch("http://localhost:8080/restApiTest").then(res => {
            return res.json();
        }).then(data => {
            let array_people = data.map((p) => {
                return p.firstName + ' ' + p.lastName;
            });
            setPeople(array_people);
        });
    }, []);


    console.log(people);

    const filterPeople = (data) => {
        let filters = people.filter((name) => {
            return name.toLowerCase().indexOf(data.toLowerCase()) !== -1;
        });
        setFiltered(filters);
    };

    return (
        <div className="App">
            <div>
                <SearchBar onEnter={filterPeople}/>
                <SortableList people={filtered}/>
            </div>
        </div>
    );
}

1 个答案:

答案 0 :(得分:0)

问题在于,当 useEffect的回调函数使用获取的数据设置您的MyTable状态时,struct MyTable : View { struct Configuration { ... init(...) { ... self.update() } mutating func update() { ... } // this method must be called before view render } @State var configuration : Configuration // note that this property can't be marked private because we want to inject `configuration` at init var body : some View { // build the view here based on configuration self.configuration.columns[3].sortAscending = false // ok, no error now about mutating a @State var self.configuration.update() // ok, no error ... } } 状态仍然保持不变,即return MyTable.init(configuration: MyTable.Configuration.init(...)) 而不是按照新的people状态。只是在初始安装时,您的filtered状态将被设置为[]状态,而不是您期望的每个后续重新渲染。要使用获取的数据更新people状态,您必须在useEffect中显式调用filtered函数,如下所示:

people