大家好,有人可以帮我吗,我试图在用户在searchform中输入任何文本后从searchform导航到此productResults页面。我能够导航到此页面,但我不知道为什么该组件不起作用并且在到达此页面后显示任何结果。将提供任何帮助。基本上,我试图导航到ProductResults组件,当用户在SearchForm组件中输入某些内容时,该组件实际上将显示结果。
SearchForm.js
import React,{ useState} from "react";
import { Form, FormControl, Button} from 'react-bootstrap';
import { useHistory } from "react-router-dom";
const SearchForm = () => {
const history = useHistory();
const [searchTerm, setSearchTerm] = useState("");
const handleSearchInput = e => {
setSearchTerm(e.target.value);
};
const handleSearchSubmit = () =>{
if(searchTerm){
let text = searchTerm;
setSearchTerm({searchTerm: " "})
history.push({
pathname: "/productResults",
state: { searchTerm: text}
});
}
else {
alert("Please enter some some search text!")
}
}
return (
<Form inline onSubmit= {handleSearchSubmit}>
<FormControl
onChange={handleSearchInput}
value={searchTerm}
type="searchTerm"
placeholder="Search"
className="mr-sm-2"
/>
<button onClick={handleSearchSubmit} type="button" class="btn btn-secondary">Search</button>
</Form>
);
}
export default SearchForm;
ProductResults.js component responsible to display results
import React,{ useState, useEffect} from "react";
import { productList } from "./apiCore";
import Layout from './Layout';
import PCard from "./PCard";
const ProductResults =() => {
const[searchTerm, setSearchTerm] = useState("");
const [searchedResults, setSearchedResults] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
handleSearch();
});
const handleSearch = () => {
if(searchTerm){
productList({ searchTerm: searchTerm || undefined})
.then(response => {
if(response.error){
console.log(response.error);
} else {
setSearchTerm(searchTerm)
setSearchedResults(response)
console.log(response);
setIsLoading(true)
}
})
}
}
const searchedProducts = (searchedResults = []) => {
return (
<div className="row">
{searchedResults.map((product, i) => (
<div className="col-4 mb-3">
<PCard key={i} product={product} />
</div>
))}
</div>
);
};
return (
<Layout
title="Searched Results "
description="Search and find books of your choice"
className="container-fluid"
>
<div className="row">
{searchedProducts(searchedResults)}
</div>
</Layout>
};
}
导出默认的ProductResults;
答案 0 :(得分:3)
您不能在功能组件中使用this.setState
this.setState ({
isLoading: false,
searchTerm: searchTerm,
searchedResults: results
});
改为使用
setSearchTerm(searchTerm)
setSearchedResults(results)
setIsloading(false)