我创建了一个自定义钩子,该钩子允许我返回人员列表
import {useEffect, useState} from "react";
import Person from "../../models/person/Person";
const usePersons = () => {
const [persons, setPersons] = useState<Array<Person>>([]);
useEffect(() => {
setPersons([
{id: 1, fullName: "Andrew Jones", createdAt: new Date(2001, 5, 12), bornAt: new Date(2002921)},
{id: 2, fullName: "Williams Hope", createdAt: new Date(2020, 8, 13), bornAt: new Date(2002420)},
{id: 3, fullName: "Markus Denzel", createdAt: new Date(2020, 8, 13), bornAt: new Date(2002420)},
{id: 4, fullName: "John Lewis", createdAt: new Date(2020, 8, 13), bornAt: new Date(2002420)},
{id: 5, fullName: "Abraham Lincoln", createdAt: new Date(2010, 0, 15), bornAt: new Date(2002420)},
{id: 6, fullName: "Jack Bauer", createdAt: new Date(2020, 8, 13), bornAt: new Date(2002420)},
{id: 7, fullName: "Sarah Watson", createdAt: new Date(2020, 8, 13), bornAt: new Date(2002420)}
]);
}, []);
return persons;
};
export default usePersons;
我创建了另一个自定义钩子,该钩子返回其id作为参数传递的人
import {useEffect, useState} from "react";
import Person from "../../models/person/Person";
import usePersons from "./persons.hooks";
const usePerson = (id: string) => {
const [person, setPerson] = useState<Person|null>(null);
const persons = usePersons();
useEffect(() => {
persons.forEach(person => {
if (person.id) {
if (person.id.toString() === id.toString()) {
setPerson(person);
}
}
});
}, [id]);
return person;
};
export default usePerson;
然后我创建了一个页面,该页面允许我显示给定人员的字段
import React, {FunctionComponent, useEffect, useState} from "react";
import { RouteComponentProps } from "react-router-dom";
import usePerson from "../../hooks/person/person.hooks";
type Params = {id: string};
const PersonDetail: FunctionComponent<RouteComponentProps<Params>> = ({match, history}) => {
const person = usePerson(match.params.id);
const handleGoBack = () => {
history.replace('/persons');
};
return (
<div>
{console.log(person)}
<h2>{person?.fullName}</h2>
<button onClick={handleGoBack} className="btn btn-primary">Return to list</button>
</div>
);
};
export default PersonDetail;
{console.log(人)}给了我空值。所以没什么可显示的。 我不明白发生了什么。
答案 0 :(得分:0)
功能挂钩usePersons
。在第一次调用中,它返回null,因为useEffect
中的usePersons
将在返回null之后执行。与useEffect
中的usePerson
相同,首次呼叫list persons
将为空。我认为useEffect
中的usePerson
应该取决于persons
。试试吧:
const usePerson = (id: string) => {
const [person, setPerson] = useState<Person|null>(null);
const persons = usePersons();
useEffect(() => {
persons.forEach(person => {
if (person.id) {
if (person.id.toString() === id.toString()) {
setPerson(person);
}
}
});
}, [id, persons]);
return person;
};