我有一个博客组件,里面有一个搜索组件。我需要访问searchResults
我的博客组件中的变量。如何将它从 Search 组件传递到 Blog 组件?
这是父级(博客组件):
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Pagination from "react-pagination-js";
import Spinner from '../Spinner/Spinner';
import { Link } from 'react-router-dom';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import Search from '../Search/Search.jsx';
const Blog = () => {
let title = 'Articles'
let [posts, setPosts] = useState([]);
let [isMounted] = useState(false)
let [currentPage, setCurrentPage] = useState(1);
let [loading, setLoading] = useState(false);
let [isVisible] = useState(true);
const [postsPerPage] = useState(5);
const GET_POSTS_API = process.env.REACT_APP_GET_POSTS_API;
useEffect(() => {
const fetchPosts = async () => {
isMounted = true;
setLoading(true);
if (isMounted) {
let res = await axios.get(GET_POSTS_API);
setPosts(res.data);
}
setLoading(false);
};
fetchPosts();
}, []);
isMounted = false
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
let totalPagesGenerated = posts.length / postsPerPage;
let totalPagesGeneratedCeiled = Math.ceil(totalPagesGenerated);
if (loading) {
return <Spinner />
}
// Change page
const paginate = (pageNumber) => {
Math.ceil(totalPagesGenerated)
if (pageNumber > 0 && pageNumber <= totalPagesGeneratedCeiled) {
setCurrentPage(pageNumber);
}
}
return (
<div>
<CustomHeader
title={title}
/>
<Search />
<div className="row">
<div className="column">
{currentPosts.map(post => (
<div key={post._id} className='post'>
<img className="post-container__image" src={post.picture} alt="avatar" />
<div className="post-container__post">
<div className="post-container__text">
<h2 className="post-container__title">{post.title}</h2>
<p className="post-container__date">{post.date}</p>
<p className="post-info-container__text">{post.postContent.substr(0, 310) + "..."}</p>
<Link to={`/post/${post._id}`} className="read-more-btn">
<button className="read-more-btn">Read more</button>
</Link>
</div>
</div>
</div>
))}
<Pagination
currentPage={currentPage}
currentPosts={currentPosts}
showFirstLastPages={true}
sizePerPage={postsPerPage}
totalSize={posts.length}
totalPages={posts.length}
changeCurrentPage={paginate}
/>
</div>
</div>
<Footer />
</div>
);
};
export default Blog;
这是孩子(搜索组件):
import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import { Link } from 'react-router-dom';
import axios from "axios";
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchResults: [],
isLoading: false,
isSearchStringFound: true,
placeholder: ''
}
}
handleSearchQuery = (event) => {
const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;
let searchString = document.querySelector(".search-input").value;
if (event.keyCode === 13) {
this.setState({ ...this.state, isLoading: true });
axios.post(SEARCH_RESULTS_ENDPOINT, {
searchString: searchString,
}).then(response => {
this.setState({ ...this.state, searchResults: response.data });
if (response.data.length === 0) {
this.setState({ ...this.state, isSearchStringFound: false });
}
else if (response.data.length > 0) {
this.setState({ ...this.state, isSearchStringFound: true });
}
this.setState({ ...this.state, isLoading: false });
});
this.setState({ ...this.state, placeholder: searchString });
}
};
render() {
if (this.state.isLoading) {
return <Spinner />
}
return (
<div>
<div>
<input
type="text"
placeholder={this.state.placeholder}
className="search-input"
onKeyDown={(e) => this.handleSearchQuery(e)}
/>
<div className="results-container">
<div>
{this.state.isSearchStringFound === false ? <div className="no-results-found">No results were found</div> : this.state.searchResults.map(result => (
<div key={result._id} className="results-box" >
<img src={result.picture} alt="avatar" className="results-container-img" />
<div className="results-box-body">
<div>
<h2>{result.title.toUpperCase()}</h2>
<p>{result.postContent.substr(0, 310) + "..."}</p>
<p>{result.date}</p>
<Link to={`/post/${result._id}`} className="read-more-btn">
<button className="read-more-btn">Read more</button>
</Link>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
);
}
}
export default Search;
不使用 Redux 是否可以做到这一点?