javascript - 如何将数据保存到数组axios?
问题描述
我正在推向一个数组
options.push(
{
value: <Adrress x={edge.node.location.lon} y={edge.node.location.lat} />,
label: <Adrress x={edge.node.location.lon} y={edge.node.location.lat} />
})
但总是当我需要这个数组时,它会刷新并且我开始 - '' 然后是实际数据,我需要一次与它交互。
export default function DataFteching({ x, y }) {
const [adrress, setAdrress] = useState(null)
const [loading, setLoading] = useState(true)
const region = /place/
useEffect(() => {
async function FtechData() {
const token = 'pk.eyJ1IjoiYW5kcmlpbXNuIiwiYSI6ImNrZGYzZ200YTJudXQyeHNjMjk2OTk2bjUifQ.njqMX6x6U946yjJdWwA7mA';
await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${x},${y}.json?access_token=${token}`)
.then(res => {
// console.log(res.data.features.find(place => place.id.match(region)).text)
setAdrress(res.data)
})
.catch(err => console.log(err))
.finally(() => setLoading(false));
}
FtechData();
}, [])
if (loading) return false;
// console.log({ adrress.features.find(place => place.id.match(region)).text })
console.log(`${(adrress.features.find(place => place.id.match(region)).text)}`)
return `${(adrress.features.find(place => place.id.match(region)).text)}`
}
解决方案
代码沙箱有依赖错误,但解决方案可能是这样的
import React, { useEffect, useState } from "react";
import { Link, graphql, useStaticQuery } from "gatsby";
import Layout from "../components/layout";
import blogStyles from "./Styles/blog.module.scss";
import Head from "../components/head";
import Adrress from "../components/Map/ftechAdrress";
import WithCallbacks from "../components/Search-panel";
const BlogPage = () => {
const [options, setOptions] = useState([]);
const data = useStaticQuery(graphql`
query {
allContentfulBlogPost(
sort: { fields: publishedDate, order: DESC }
filter: { node_locale: { eq: "en-US" } }
) {
edges {
node {
title
slug
publishedDate(formatString: "MMM Do, YYYY")
image {
file {
url
}
}
location {
lat
lon
}
breed
find
}
}
}
}
`);
useEffect(() => {
const tmp = [];
data.allContentfulBlogPost.edges.forEach((edge) => {
tmp.push({
value: (
<Adrress x={edge.node.location.lon} y={edge.node.location.lat} />
),
label: <Adrress x={edge.node.location.lon} y={edge.node.location.lat} />
});
});
setOptions([...tmp]);
}, [data]);
return (
<Layout>
<Head title="Blog" />
<h1>lost pets</h1>
{console.log(options)}
<WithCallbacks options={options} />
<ol className={blogStyles.posts}>
{options.map((edge) => {
const styles = edge.node.image
? `url("${edge.node.image.file.url}")`
: `url("https://cdn.pixabay.com/photo/2019/07/30/05/53/dog-4372036__340.jpg")`;
return (
<li>
<Link to={`/blog/${edge.node.slug}`}>
<div
style={{ backgroundColor: "pink", backgroundImage: styles }}
>
<h2>{edge.node.title}</h2>
<p>{edge.node.publishedDate}</p>
<p>Порода: {edge.node.breed}</p>
<p>
Статус: <span>{edge.node.find ? "Найден" : "Потерян"}</span>
</p>
<p>
city:{" "}
<Adrress
x={edge.node.location.lon}
y={edge.node.location.lat}
/>
</p>
</div>
</Link>
</li>
);
})}
</ol>
</Layout>
);
};
export default BlogPage;