簡體   English   中英

將狀態數組發送到另一個組件以在 REACT.js 中呈現

[英]Sending state array to another component to be rendered in REACT.js

我正在嘗試在 NavBar 組件中搜索輸入文本並發送結果數組以在另一個組件中呈現。 我可以更改 Navbar 組件中的狀態,但我不知道如何將 SearchResults 數組從 NavBar 組件傳遞到 SEARCH 組件中的結果數組。

導航欄組件:

import React from "react";
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  Button,
  NavLink
} from "reactstrap";
import "./NavBar.css";
import Search from "../Search/searchMovies";

export default class NavBar extends React.Component {
  constructor(props) {
    super(props);
    this.submitSearch = this.submitSearch.bind(this);
    this.handleSearchInput = this.handleSearchInput.bind(this);
    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false,
      searchText: "",
      searchResults: [],
      isLoaded: false
    };
  }
  handleSearchInput(e) {
    this.setState({ searchText: e.target.value });
  }

  submitSearch = () => {
    fetch(
      `https://api.themoviedb.org/3/search/movie?api_key=api&language=en-US&query=${
        this.state.searchText
      }&page=1&include_adult=false`
    )
      .then(movies => movies.json())
      .then(({ results }) => {
        this.setState({ isLoaded: true, searchResults: results });
      });
  };

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }
  render() {
    return (
      <div>
        <Navbar className="Nav" color="" dark expand="md">
          <NavbarBrand className="logo" id="logo" href="/">
            <img alt="logo" src="" />
          </NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>
            <Nav className="ml-auto " navbar>
              <NavItem className="searchInput">
                <input
                  placeholder="Search for movies..."
                  ref={input => (this.search = input)}
                  onChange={this.handleSearchInput}
                />
              </NavItem>
              <NavItem>
                <NavLink href="/results">
                  <Button color="danger" size="lg" onClick={this.submitSearch}>
                    Search
                  </Button>
                </NavLink>
              </NavItem>
            </Nav>
          </Collapse>
        </Navbar>
      </div>
    );
  }
}

搜索組件:

import React, { Component } from "react";
import {
  Card,
  Button,
  CardTitle,
  CardText,
  Row,
  Col,
  CardImg
} from "reactstrap";
import "../Cards/Cards.css";
import { Link } from "react-router-dom";
import NavBar from "../Navigation/NavBar";

export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    this.setState({ results: this.props.results });
  }

  render() {
    var { isLoaded, results } = this.state;
    if (!isLoaded) {
      return <div> .... Loading</div>;
    } else if (results.length === 0) {
      return (
        <div>
          Your search - {NavBar.props.results} - did not match any movies.
          Suggestions: Make sure that all words are spelled correctly.{" "}
        </div>
      );
    } else {
      return (
        <div>
          <h3>Your Search Results!</h3>
          <Row>
            {this.props.results.map(Movie => (
              <Col sm="3">
                <Card key={Movie.id} className="Top_Rated" body>
                  <CardImg
                    top
                    width="100%"
                    src={`https://image.tmdb.org/t/p/w200${Movie.poster_path}`}
                    alt=""
                  />
                  <CardTitle className="title">{Movie.title}</CardTitle>
                  <CardText className="Text">
                    Rating:{Movie.vote_average}
                  </CardText>
                  <Link to={"/movie/" + Movie.id}>
                    <Button color="danger">Visit</Button>
                  </Link>
                </Card>
              </Col>
            ))}
          </Row>
        </div>
      );
    }
  }
}

請在獲取和更改狀態后的submitSearch函數中建議如何在沒有 redux 的情況下將數組從組件發送到組件

您應該將這兩個組件都包裝在一個Context實例中,並且您將能夠在全局范圍內共享結果。

我建議使用Lifting State Up
這是最近祖先組件的示例。

    class WrapComponent extends React.Component {
      constructor(props) {
        super(props);

        this.state = {
          searchResults: []
        }
      }

      // Arrow function, no 'bind' needed
      setSearchResults = (searchResults) => {
        this.setState(() => ({ searchResults: searchResults  }));
      }

      render() {
        return (
          <div>
            <NavBar setSearchResults={this.setSearchResults} />
            <Search searchResults={this.state.searchResults} />
          </div>
        )
      }
    }

然后,您可以使用道具中的“setSearchResults”從 NavBar 更新“searchResults”。

您應該將searchResults作為道具傳遞給 Search 組件
導航欄組件:

 <Button color="danger" size="lg" onClick={this.submitSearch}>
 <Search results={this.state.searchResults} />
 </Button>

然后在搜索組件中,您可以訪問 sate

componentDidMount() {
    this.setState({ results: this.props.results});
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM