简体   繁体   English

数据保存到state后显示来自mongo的数据 - React hooks

[英]Display data from mongo after data is saved in state - React hooks

I am creating an app with a search box, that when submitted will get data from mongo and display the data.我正在创建一个带有搜索框的应用程序,提交后将从 mongo 获取数据并显示数据。 The problem is I am unsure of how to ensure the data is fully saved in state before I display it.问题是我不确定如何确保数据在显示之前完全保存在 state 中。 This leads to issues where it says "property x is undefined".这会导致出现“属性 x 未定义”的问题。 I can't seen to find a definitive way of doing it and I am a beginner to React also.我看不到找到明确的方法,而且我也是 React 的初学者。

My current thinking is to use useEffect with a dependency array of loading to check when data is fully loaded before displaying data.我目前的想法是将 useEffect 与加载的依赖数组一起使用,以在显示数据之前检查数据何时完全加载。 But I am not sure where to set the state that the data has loaded and change loading to true但是我不确定在哪里设置数据已加载的state并将加载更改为true
I have 3 parts currently getData (gets data from Mongo), displayData (attemping to display one field at the moment) and render我目前有 3 个部分getData (从 Mongo 获取数据)、 displayData (目前试图显示一个字段)和渲染

getData获取数据

 const getData = async (e) => { e.preventDefault(); // setLoading(true); fetch(API_URL + id).then(response => response.json()).then(data => { setContact(data); setLoading(true); }); console.log("DATA SAVED"); };

displayData显示数据

 const displayExperience = (contact) => { return contact.experience.map((exp, index) => ( <div key={index}> <h3>{exp.company}</h3> </div> )); };

NOTE: experience is an array of objects, containing info on a contacts work experience.注意: experience 是一组对象,包含有关联系人工作经验的信息。 THis array of objects I beleive is causing the issue as I can display a single field of contact but cannot display anything within experience object due to undefined error我认为这个对象数组导致了这个问题,因为我可以显示一个单一的联系领域,但由于未定义的错误而无法显示经验 object 中的任何内容

render使成为

 return ( <div className="App"> <Form onSubmit={getData}> <div className="App"> <Form.Group> <Form.Label>ID</Form.Label> <Form.Control type="text" placeholder="Add ID" onChange={(e) => setId(e.target.value)}/> </Form.Group> <Button className="mt-2" variant='dark' type="submit" >Submit</Button> </div> </Form> <div> {displayExperience(contact)} </div> </div> )

States 状态

 const [contact, setContact] = useState([]); const [loading, setLoading] = useState(false); const [id, setId] = useState('');


Any suggestions for how best to save state fully so I can display without undefined errors. 关于如何最好地完全保存 state 以便我可以显示而不会出现未定义错误的任何建议。 Again the issue seems to be as one of the fields returned is an array of objects. 同样,问题似乎是因为返回的字段之一是对象数组。 I beleive I should add a useEffect function and can be seen in *getData* where I attempted to set loading state. 我相信我应该添加一个 useEffect function 并且可以在我试图设置加载 state 的 *getData* 中看到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM