首页 > 解决方案 > 反应显示获取的数据问题

问题描述

我正在开发一个 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。

标签: reactjsreact-hooks

解决方案


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.


推荐阅读