我是@frontend 的新手,发现使用 Formik
在 Next.js
中创建一个简单的搜索表单并返回从我自己的 API 获取的数据有点困难在页面上。由于相关信息不多,或者有,但没有涵盖整个过程,所以我决定创建这个问题。
What am I dealing with:
- 在 express 上分离基于前端和后端的 API(都在 现在本地主机)
- react (+ dom)和 Next.js
- React Material-UI
- 福米克
Architecture:
前端发送请求(基于表单输入)-> 服务器收到它(对其进行操作)并用 json
对象响应-> 前端接受它,并将结果显示在页面上。
- 后端(已启用正确的 CORS)
一个简单的 node.js express 服务器,只有一个路由 (localhost:port/users/:id) 当你像 ./users/100
那样请求它时,它返回 json
使用 {id}+1 递增,如 {id:101}
,示例代码如下:
var express = require('express');
var router = express.Router();
/* CORS ARE FINE */
router.get('/:id', function(req, res) {
res.json({id: parseInt(req.params.id)+1});
});
module.exports = router;
- 前端(next.js + formik)
我已经编写了 MyForm
组件并将其插入到我的主页上。下面是 MyForm
组件的代码:
import React from 'react';
import fetch from 'isomorphic-unfetch'
import { Formik, Form, Field } from 'formik';
import { TextField } from 'formik-material-ui';
import Button from "@material-ui/core/Button";
const MyForm = () => (
<Formik
initialValues={{ text: '', password: '' }}
onSubmit={ async (values, { setSubmitting }) => {
const res = await fetch(`http://localhost:8000/users/${values.text}`, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}}).then(response => response.json());
console.log(res);
//props = res;
//return props;
setTimeout(() => {
alert(JSON.stringify(res, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting }) => (
<Form>
<Field
name="text"
label="Text"
type="text"
variant="outlined"
component={TextField}
/>
<Button
type="submit"
variant="contained"
color="primary"
disabled={isSubmitting}
>
Submit
</Button>
</Form>
)}
</Formik>
);
export default MyForm
至于现在,myForm 工作正常,通过提交表单从 API 收到必要的数据。结果存储为 res
变量,并在页面上显示为弹出窗口。
但我想看到它,回到页面上。像这样:
网络上没有那么多教程逐步介绍这个过程。我知道在 Next.js
fetched data received通过 getInitialProps
。 (但是没有提交表单的例子)
我将我的组件放在页面上:
export default function Index() {
return (
<Container maxWidth="sm">
<Box my={4}>
<Form />
<Here is an element with search form results />
</Box>
</Container>
);
}
然后 I read that I can't return props from child component回到父级。或者我可以吗?我也不能将 res
变量作为组件值放在表单内部或外部:
那我现在该怎么办?无论如何,我没有在 Formik
教程中找到任何相关示例。我知道它以某种方式与 state
操作相关,例如 componentDiDMount
,这就是前端开发人员使用 Redux
等模块的原因。但是有人可以解释一下,我做错了什么吗?
此外,如果您有任何相关信息并想给我一些建议或分享它(例如 Formik 在这种情况下没用,您应该使用 X
代替)不要害羞,只是发表它。我会查看并投票。
According to @Shyam answer I updated my code. As for now, form has the following code:
const MyForm = (props) => (
<Formik>
...
onSubmit={ async (values, { setSubmitting }) => {
const res = await fetch(`http://localhost:8000/users/${values.text}`, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}}).then(response => response.json());
console.log(res);
setSubmitting(false);
props.myCallbackFunction(res);
}}
...
和index.js
根据下面的推荐,
在这种情况下,React
返回一个错误,与 props
相关,但表单提交工作正常。我想我可以在这里找到相关信息:
https://reacttricks.com/sharing-global-data-in-next-with-custom-app-and-usecontext-hook/
最佳答案
一种方法是将回调函数作为 prop 发送到 MyForm,并在收到获取的结果后用 res 调用它。
export default function Index() {
const [result, setResult] = useState(null)
const callMeOnRes = (data) => {
setResult(data)
}
return (
<Container maxWidth="sm">
<Box my={4}>
<Form myCallbackFunction={(res) => callMeOnRes(res)} />
{result && <div>{result}</div>}
<Here is an element with search form results />
</Box>
</Container>
);
}
在 MyForm 中,在控制台日志之后调用 props.myCallbackFunction(res)
。
最好的方法是将 api 调用和前端逻辑分离,并使用一些状态管理来加载、错误、调用状态。理想情况下,您不应该在这种情况下使用 setTimeouts。
希望这对您有所帮助。
关于javascript - 如何从 Next.js 中的 Formik 提交返回 API(获取)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933874/