[英]useEffect keeps returning nothing on an axios call
I've been trying to look for an answer everywhere but this is really driving me crazy.我一直试图到处寻找答案,但这真的让我发疯。 Been using StackOverflow for a while, yet this became my first question.
使用 StackOverflow 有一段时间了,但这成为我的第一个问题。
I'm trying to build a dynamic table using react.我正在尝试使用 react 构建一个动态表。 For this, I am passing the state using the
useState
hook to an external component -which actually builds the table- through its props.为此,我使用
useState
钩子将 state 通过其道具传递给外部组件 - 它实际上构建了表格。 The reason not to build it on the same component is that I'm re-using the external component.不在同一个组件上构建它的原因是我正在重用外部组件。
So far, this is the code where the hooks are being used到目前为止,这是使用钩子的代码
Commands.js命令.js
export default function Commands() {
const [data, setData] = useState([])
const fetchData = () => {
axios.get(`${server}${endpoint}`).then(ret => {
setData(ret.data)
}).catch(e => {console.log(e)})
}
useEffect(() => {
fetchData()
}, [])
return (
<Container>
<CommandsTable data={data}/>
</Container>
)
}
And this is the code where the data is used, although I think it should be unrelated.这是使用数据的代码,尽管我认为它应该是无关的。
CommandsTable.js CommandsTable.js
// ...
<tbody>
{
props.data.map(command => {
<tr key={command._id}>
<td>{command.name}</td>
<td>{command.ret}</td>
// etc
</tr>
})
}
</tbody>
//...
The problem : data
always comes out not as undefined, but as empty (I assume it's the []
initial value I assign with useState
)问题:
data
总是不是未定义的,而是空的(我假设它是我用useState
分配的[]
初始值)
One more thing I find funny is that even if I'm using axios-debug-log
, it never logs any call, but using it anywhere else on the code, the same call works without issue.我觉得有趣的另一件事是,即使我使用
axios-debug-log
,它也不会记录任何调用,但是在代码的其他任何地方使用它,相同的调用也不会出现问题。
What am I missing?我错过了什么?
Thanks!谢谢!
I'm assuming that the ret
object is coming back as something you're not expecting.我假设
ret
object 会以您意想不到的方式回归。
I would suggest taking a peak at the ret
variable when it arrives.我建议在
ret
变量到达时达到峰值。
export default function Commands() {
const [data, setData] = useState([])
const fetchData = () => {
axios.get(`${server}${endpoint}`).then(ret => {
console.log({ ret })
setData(ret.data)
}).catch(e => {console.log(e)})
}
useEffect(() => {
fetchData()
}, [])
return (
<Container>
<CommandsTable data={data}/>
</Container>
)
}
Figured it out thanks to @Ajay 's comment.感谢@Ajay 的评论,弄明白了。
It was a CORS policy issue.这是一个 CORS 政策问题。 This is what I've done to solve it.
这就是我为解决它所做的。
Server side (express server) Install cors服务器端(快递服务器)安装cors
npm i cors
Require and use it要求并使用它
const cors = require("cors")
app.use(cors())
Restart server, solved.重启服务器,解决。 Thanks guys!
多谢你们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.