reactjs - 反应显示获取的数据问题
问题描述
我正在开发一个 React 项目,但在尝试显示我刚刚获取的数据时遇到了问题。
...
const [clientImport, setClientImport] = useState(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
fetchData();
}, []);
const fetchData = async() => {
setIsLoading(true);
const result = await axios.get('http://localhost:8080/client');
setClientImport(result);
console.log(result);
console.log(clientImport);
};
const formChange = (e) => {
setIsLoading(false);
console.log(clientImport.data[2].nom);
const value = e.target.value;
setState({
...state,
[e.target.name]: value
})
}
return <div>
<Calendar getDate={getDate}/>
<Form> {isLoading ? (<div>Loading ...</div>) : (<div>aze and {clientImport.data[2].nom}</div>)}
...
所以我的 fetch 工作正常,我在formChange
方法中对其进行了测试,我得到了clientImpot.data[2].nom
.
但是每当我尝试在 JSX 中显示相同的东西时,我都会得到一个
类型错误:clientImport 为空。
上面的版本给了我错误。当我删除{clientImport.data[2].nom}
它工作正常。
每当我尝试clientImport
在返回中显示任何值时,它都不起作用。
这只是为了调试,我把它放在那里,目标是最终把它放在那里进行映射:
<Form.Group as={Col} lg={5} controlId="formClient">
<Form.Label>Client - </Form.Label>
<Form.Control as="select" onChange={updateClientChoice}>
<option key={-2} ></option>
<option key={-1} value="newClient">Ajouter un nouveau client</option>
{clientImport.data.map((c, i) => (
<option key={i} value={c.id}>{c.name} - {c.prenom} - {}</option>))}
</Form.Control>
</Form.Group>
谢谢你的帮助 ;)。
编辑:有关更多信息:
当我这样做时:const [clientImport, setClientImport] = useState(null);
有了这个 :clientImport.data.map
它返回:TypeError: clientImport is null
但是,如果我用 ''(or[]) 声明它,例如:
const [clientImport, setClientImport] = useState('');
表明 :TypeError: imports.client.data is undefined
如果这可以帮助,但我有点卡在这里:p。
解决方案
Problem solved.
I needed to declare my import as :
const [clientImport, setClientImport] = useState([]);
the fetch like :
const result = await axios.get('http://localhost:8080/client');
setclientImport(result.data);
and for the map :
clientImport.map
The issue apparently as that i declared as null and changed the type, and it's a bad idea to change types :p.
推荐阅读
- r - 使用区间距离而不是单元距离连接来自不同组的异常区间
- scrum - 在 sprint 期间重新分配用户故事?
- c# - 为什么我们不能在 c# struct 的声明中初始化实例字段?
- python - 按元组的第一个元素对元组列表进行排序而不删除重复项
- java - 如何使用最新的 Eclipse 正确导入 java.awt?
- java - 执行 TestNG 套件后显示错误“java.lang.NullPointerException DefaultElementLocator.findElement(DefaultElementLocator.java:69)”
- git - 在 git 中为 Visual Studio 2019“导出”本地分支
- python - 根据python中的每日表删除每行的所有(每小时)日条目
- swift - 是否可以使用 URL 会话委托方法进行进度和完成处理程序来完成?还是更好的选择?
- java - 为什么 Exchange Web 服务 API 无法从邮箱中删除邮件?