我必须显示url和缩短的url,但每次我尝试输入新的url时,它都会更改已显示的url的值。怎样我能告诉你这个吗?我使用的是setUrl([newUrl,...url]);
,我想这就是的问题所在
我的完整代码:
import { useEffect, useState } from "react";
import GetStarted from "./components/GetStarted";
import NavBar from "./components/NavBar";
import StatSection from "./components/StatSection";
import SearchBar from "./components/UrlShortener/SearchBar";
function App() {
const [url, setUrl] = useState([]);
const [shortenedUrl, setShortenedUrl] = useState([]);
const apiUrl = `https://api.shrtco.de/v2/shorten?url=${url}`;
const handleChange = (e) => {
const newUrl = e.target.value;
setUrl([newUrl,...url]);
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch(apiUrl, {
// Adding method type
method: "POST",
});
const data = await response.json();
const shortLink = data.result.full_short_link;
setShortenedUrl([shortLink,...shortenedUrl]);
} catch (error) {
console.log(error);
}
};
return (
<>
<NavBar />
<GetStarted />
<SearchBar
onChange={handleChange}
handleSubmit={handleSubmit}
shortenedUrl={shortenedUrl}
url={url}
/>
</>
);
}
export default App;
下面的代码将解决您的问题。
import { useEffect, useState } from "react";
import GetStarted from "./components/GetStarted";
import NavBar from "./components/NavBar";
import StatSection from "./components/StatSection";
import SearchBar from "./components/UrlShortener/SearchBar";
function App() {
const [url, setUrl] = useState('');
const [shortenedUrl, setShortenedUrl] = useState('');
const apiUrl = `https://api.shrtco.de/v2/shorten?url=${url}`;
const handleChange = (e) => {
const newUrl = e.target.value;
setUrl(newUrl);
if(shortenedUrl){
setShortenedUrl('');
}
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch(apiUrl, {
// Adding method type
method: "POST",
});
const data = await response.json();
const shortLink = data.result.full_short_link;
setShortenedUrl(shortLink);
} catch (error) {
console.log(error);
}
};
return (
<>
<NavBar />
<GetStarted />
<SearchBar
onChange={handleChange}
handleSubmit={handleSubmit}
shortenedUrl={shortenedUrl}
url={url}
/>
</>
);
}
export default App;
function App() {
const [url, setUrl] = useState('');
const [shortenedUrl, setShortenedUrl] = useState('');
const apiUrl = `https://api.shrtco.de/v2/shorten?url=${url}`;
const handleChange = (e) => {
setUrl(e.target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch(apiUrl, {
// Adding method type
method: "POST",
});
const data = await response.json();
const shortLink = data.result.full_short_link;
setShortenedUrl(shortLink);
} catch (error) {
console.log(error);
}};
并且应该设置input=><input value = {url} />