Yan*_*ick 7 reactjs react-router react-hooks
我正在使用react-router5.1 和react16.10。
对于主从页面,我使用useParams()从 url 获取 id 以打开当前组的页面。打开发生在useEffect(). 因此,id必须作为该效果的依赖项给出。但是,在创建新组时,当有足够的数据使组有效时,API 会发送该id组的 并将 URL 设置为/group/:id。然而,结果是,效果再次运行。
function Groups(props) {
const { id } = useParams();
const history = useHistory();
const [group, setGroup] = useState(NEW_GROUP);
const getData = useCallback(async () => {
await Promise.resolve(Api.getGroups());
}, []);
const getGroup = useCallback(async group => {
history.push(`/groups/${group.id}`);
await Promise.resolve(Api.getGroup(group)).then(data => {
setGroup(data.group);
});
}, [getData, history]);
useEffect(() => {
getData();
if (id !== undefined) {
getGroup({ id });
}
}, [props.actions, id, getData, getGroup]);
// Saving data
const saveGroup = useCallback(async () => {
setSaved(SAVING);
await Promise.resolve(Api.storeGroup(group)).then(data => {
if (!group.hasOwnProperty('id')) {
history.push(`/groups/${data.id}`);
setGroup(prevGroup => ({ ...prevGroup, id: data.id }));
}
getData();
setSaved(SAVED);
}).catch(() => setSaved(FAILED));
}, [getData, group, history]);
}
Run Code Online (Sandbox Code Playgroud)
如何在不违反“钩子规则”的情况下防止这种情况发生?
小智 7
我遇到了同样的问题,我解决的方法是将 id 从 useParams 传递给函数并仅在 useEffect 中设置 id。
function Groups(props) {
const { id } = useParams();
...
useEffect(() => {
getData(id);
if (id !== undefined) {
getGroup({ id });
}
}, [id]);
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3679 次 |
| 最近记录: |