使用NextJS,我正在努力弄清楚如何让应用程序真正调用我在表单提交时设置的应用程序接口。现在,当我点击提交时,我得到了一个非常随机的错误,
Error: Search(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
正如你可以假设的那样,这最终是无用的,也是有帮助的。我不明白为什么它不能工作,因为它可以在其他地方的其他组件中工作。谢谢你的帮助。下面是我的代码:
api.js
const API = process.env.WP_API_URL;
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' };
const res = await fetch(API, {
body: JSON.stringify({ query, variables }),
headers,
method: 'POST',
});
const json = await res.json();
if (json.errors) {
console.log(json.errors);
console.log('error details:', query, variables);
throw new Error('Failed to fetch API');
}
return json.data;
export async function getCampgroundsByCity(query) {
const data = await fetchAPI(
`
query MyQuery($string: String) {
campgrounds(where: {city: $string}) {
nodes {
acfDetails {
address
city
closeDate
latitude
longitude
numberOfSites
openDate
website
picture {
altText
mediaItemUrl
}
}
title
}
}
}
`,
{
variables: {
string: query,
},
}
);
return data?.campgrounds;
}
}
newsearch.js:
import { useRouter } from 'next/router';
import { useState } from 'react';
import { ViewportContextProvider } from '../lib/state';
import { getCampgroundsByCity } from '../lib/api';
export default function Search({ viewport, setViewport, cities }) {
const [view, setView] = useState();
const handleChange = e => {
setView(e.target.value);
};
const updateViewport = async event => {
event.preventDefault();
// const campgroundsbycity = await getCampgroundsByCity('Bethlehem');
// console.log(view);
};
return (
<form onSubmit={updateViewport}>
<label htmlFor="city">City</label>
<select value={view} onChange={handleChange}>
{cities.nodes.map(town => {
return (
<option value={town.acfDetails.city}>{town.acfDetails.city}</option>
);
})}
</select>
<button type="submit">Submit</button>
</form>
);
}
发布于 2021-03-02 22:11:08
根据代码结构的不同,Next.js有不同的工作方式(请参阅此https://nextjs.org/docs/basic-features/data-fetching )。因此,不同的.env变量可能会公开,也可能不会公开。如果你需要一个公开的.env (就像你的API调用中的URL ),你必须在名字上使用"NEXT_PUBLIC_“,比如"NEXT_PUBLIC_WP_API_URL”。
你可以在这里阅读更多信息:https://nextjs.org/docs/basic-features/environment-variables
因此,您必须像这样更改.env:
# OLD
# WP_API_URL=https://my.url.com
# NEW
NEXT_PUBLIC_WP_API_URL=https://my.url.com
你的api.js是这样的:
// const API = process.env.WP_API_URL;
const API = process.env.NEXT_PUBLIC_WP_API_URL;
https://stackoverflow.com/questions/66440823
复制相似问题