1 回答
TA贡献1828条经验 获得超3个赞
好的,如果提取有效,请尝试此代码。
function App() {
const [data, setData] = React.useState([]);
const [searchResults, setSearchResults] = React.useState([]);
const [searchTerm, setSearchTerm] = React.useState("");
const fetchData = () => {
let corsAnywhere = "https://cors-anywhere.herokuapp.com/";
let something = "ksngfr.com/something.txt";
fetch(corsAnywhere + something)
.then((response) => response.text())
.then((result) => {
const theDataArr = result.replace(/\n/g, " ");
const f = theDataArr.split(" ");
setData(f);
});
};
React.useEffect(() => {
fetchData();
}, [searchTerm]);
React.useEffect(() => {
if (data.length) {
const mappedResult = data.map((d) => {
var propertyK = d.split(":")[0];
var propertyv = d.split(":")[1];
return {
key: propertyK,
value: propertyv
};
});
const results = mappedResult.filter((each) => each.key === searchTerm);
console.log("result is: ", results);
setSearchResults(results);
}
}, [data, searchTerm]);
return (
<div>
<input
type="text"
value={searchTerm}
placeholder="Search..."
onChange={(e) => setSearchTerm(e.target.value)}
/>
<div>
{searchResults.map(({ key, value }, index) => (
<div>
<div>{`value is: ${value} and key is: ${key}`}</div>
</div>
))}
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
添加回答
举报