在我的 ReactHooks/Typescript 应用程序中,我有一个导航组件,它呈现 PatientInfo 组件。 PatientInfo 子组件根据传递的 props 有条件地呈现,这由另一个子组件 - MyPatients 中的搜索框决定。
在此结构中,我收到以下错误:
导航.tsx:
// code....
<Route exact path="/" component={MyPatients} />
<Route
exact
path="/Pasient"
render={() => (
<PatientInfo
setName={setName}
setSchema={setSchema}
patientID={patientID}
/>
)}
/>
// code....
我的病人:
const MyPatients = (props: { history: History }) => {
localStorage.clear();
const [patientID, setPatientID] = useState(
localStorage.getItem('myData') || '',
);
useEffect(() => {
localStorage.setItem('myData', patientID);
}, [patientID]);
return (
<>
<div className="search-container"></div>
<Row gutter={[60, 40]} justify={'center'}>
<Col span={1000}>
<p>Søk med personnummer for å finne en pasient</p>
<Search
style={{ width: 400 }}
className="search-bar"
placeholder="Søk etter en pasient!"
onSearch={(value: string) => setPatientID(value)}
/>
</Col>
</Row>
{patientID &&
props.history.push({ pathname: 'Pasient', state: patientID })}
</>
);
};
export default MyPatients;
我不熟悉这个问题,也不明白发生了什么。我有根据的猜测是,React 不喜欢这样的事实:父组件的状态由传递给子组件的函数进行更新,而子组件又依赖于与其一起传递的 props。我有事吗?如果没有的话,有什么想法导致这个问题吗?
感谢任何帮助。
最佳答案
您在每个渲染上使用 history.push
进行导航。
正如 @HMR 在评论中提到的,您必须从 JSX 模板中删除导航并将其添加到单独的效果中。
const MyPatients = (props: { history: History }) => {
localStorage.clear();
const [patientID, setPatientID] = useState(
localStorage.getItem("myData") || ""
);
useEffect(() => {
localStorage.setItem("myData", patientID);
}, [patientID]);
// separate effect here
useEffect(() => {
if (patientID) {
props.history.push({ pathname: "Pasient", state: patientID });
}
}, [props, patientID]);
return (
<>
<div className="search-container"></div>
<Row gutter={[60, 40]} justify={"center"}>
<Col span={1000}>
<p>Søk med personnummer for å finne en pasient</p>
<Search
style={{ width: 400 }}
className="search-bar"
placeholder="Søk etter en pasient!"
onSearch={(value: string) => setPatientID(value)}
/>
</Col>
</Row>
</>
);
};
export default MyPatients;
编辑
这可能会导致您的错误:
<PatientInfo
setName={setName}
setSchema={setSchema}
patientID={patientID}
/>
如果您在渲染 PatientInfo
时调用 setName
或 setSchema
,则 Navigation
状态将更新 PatientInfo
渲染完成之前。
关于javascript - 警告 : Cannot update a component while rendering a different component. ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62694745/