我已经试着解决这个问题三天了,我就要崩溃了。我似乎无法得到我的反应的孩子部分-接收道具传递给它。相反,它正在将它们呈现为未定义的。
流程如下:
submitFile -> (Callback) -> App (set state using useState hooks) -> Dashboard
我已经检查了回调,并且回调正常工作,所以数据返回到App,console.log确认状态已经设置。但是,我真的不明白为什么要用未定义的道具创建仪表板组件。任何帮助都将不胜感激。我尝试过许多不同的东西,读过无数的线程和文档,坦白地说,我要爆炸了!
请参见下面的代码: App.js
export default function App() {
const [authState, setState] = useState(false);
const [jobId, setJobId] = useState(false);
const [token, setToken] = useState(false);
const [apiKey, setApiKey] = useState(false);
const authCallbackState = authStateData => {
setState(authStateData);
};
const jobCallback = (jobId_, token_, apiKey_) => {
setJobId(jobId_);
setToken(token_);
setApiKey(apiKey_);
};
return (
<ThemeProvider theme={theme}>
<Router>
<Switch>
<Route
path="/dashboard"
render={() =>
authState && apiKey ? (
<Dashboard jobId={jobId} token={token} apiKey={apiKey} />
) : (
<h1>loading</h1>
)
}
></Route>
<PrivateRoute path="/submitFile" authState={authState}>
<CssBaseline />
<SubmitFile dbCallback={jobCallback} />
</PrivateRoute>
<Route path="/">
<AuthComponent appCallback={authCallbackState} />
</Route>
</Switch>
</Router>
</ThemeProvider>
);
}
正如您所看到的,我已经这样做了,所以仪表板只在链接中切换之后呈现,至少值应该是假的,而不是未定义的?
仪表板函数,它使用道具
export default function Dashboard(props) {
/**
* Polls the API at 30 second intervals to check job status
*
*/
const getFile = async e => {
const url = baseUrl + '/get_results';
const headers = { headers: { 'x-api-key': props.apiKey, Authorization: props.token } };
console.log(headers['Authorization']);
const interval = setInterval(() => {
axios.get(url, props.jobId, headers).then(response => {
if (response.status === 200) {
setProgress(100);
showWaitMessage(false);
setFile(response.data);
clearInterval(interval);
}
if (response.status === 202) {
if (progress < 100) {
setProgress(progress + 10);
} else if (!ackWaitMessage) {
showWaitMessage(true);
}
}
if (response.status === 403) {
// show some error message
clearInterval(interval);
}enter code here
if (response.status === 400 || 404) {
showErrorMessage(true);
clearInterval(interval);
}
});
}, 30000);
};
发布于 2020-07-29 06:08:24
setInterval
每一次都会得到关闭,并使用相同的道具进行投票。
您可以使用useEffect
钩子更新轮询函数:
useEffect(() => {
const watcher = setInterval(....);
return () => clearInterval(watcher);
}, [props.jobId, props.token, props.apiKey]);
或者您可以将当前的道具存储在useRef
中。
const propsRef = useRef(props);
propsRef.current = props;
并以propsRef.current.jobId
身份在getFile
中访问它们。
发布于 2020-07-30 00:17:46
我真的很抱歉浪费了所有人的时间。以前,当我在子组件中有以下useEffect时,我觉得自己很聪明:
useEffect(() => {
console.log(props.jobId);
getFile();
}, []);
它显然由于空依赖数组而锁定在子节点的状态中。哈!
我把它更新为
useEffect(() => {
console.log(props.jobId);
getFile();
}, [props.jobId, props.apiKey, props.token]);```
and it works fine.
https://stackoverflow.com/questions/63155174
复制相似问题