簡體   English   中英

如何在React JS中修復“相同的道具傳遞給孩子”?

[英]How to fix “same prop getting passed to children” in react js?

所以我很新來反應js。 我正在創建一個博客應用。 我正在狀態中存儲博客數據,並將其傳遞給子組件。 在下面的代碼中,我具有Feeds組件,該組件用於從json提取數據並將其存儲在狀態中。 我通過道具將數據傳遞給子級組件Feed。 現在,我有一個文章組件,它是Feed的子代,它作為模式打開。 但是,問題是無論我單擊哪個Feed,它都會打開同一篇文章(以最近發表的文章為准)。

Feeds.jsx

import React, { Component } from "react";
import axios from "axios";
import Feed from "./Feed";

class Feeds extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoaded: false,
      feeds: []
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:5000/api/items")
      .then(res => res.data)
      .then(data => {
        this.setState({ isLoaded: true, feeds: data });
      console.log("data " + data);
     })
      .catch(err => console.log("Error !! : " + err));
  }

  render() {
    let { isLoaded, feeds } = this.state;

    if (!isLoaded) {
      return (
        <div>
          <h4> Loading ..</h4>
        </div>
      );
    } else {
      return (
        <div className="container-fluid">
          <Feed feedData={feeds} key={feeds.id} />
        </div>
      );
    }
  }
}
// const style for class Feed

export default Feeds;

Feed.jsx

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import Article from "../component/Article";

class Feed extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    };
  }

  showModal() {
    this.setState({ showModal: true });
  }

  hideModal() {
    this.setState({ showModal: false });
  }

  render() {
    console.log("Id: " );
    console.log(this.props.feedData, "feedData");
    let modalClose = () => this.setState({ showModal: false });
    return (
      <div className="container-fluid">
        <ul className="list-group" key={this.props.feedData.id}>
          {this.props.feedData.map(feed => (
            <li
              className="list-group-item"
              style={styles.container}
              key={feed.id}
            >
              <div className="container">
                <div className="col-md-12">
                  <button
                    type="button"
                    className="btn btn-default"
                    onClick={() => this.showModal()}
                  >
                    <h3 style={styles.heading}>{feed.title} </h3>
                  </button>
                  <p>by - {feed.author}</p>
                  <p>{feed.subTitle}</p>
                  <div>
                    <span className="badge">Posted {feed.date}</span>
                    <div className="pull-right">
                      <button className="btn btn-primary">Upvote</button>{" "}
                      <button className="btn btn-info">Comment</button>{" "}
                      <button className="btn btn-danger">Report</button>{" "}
                    </div>
                  </div>
                  <br />

                  <Article
                    key={feed.id}
                    show={this.state.showModal}
                    onHide={modalClose}
                    data={feed}
                  />
                </div>
                <hr />
              </div>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

Article.jsx

import React, { Component } from "react";
import { Button, Modal } from "react-bootstrap";

class Article extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    console.log("This is working. Visibility: " + this.props.visible);
    console.log("This is the id of the feed: " + this.props.key);
    return (
      <div className="article">
        <Modal
          {...this.props}
          size="lg"
          aria-labelledby="contained-modal-title-vcenter"
          centered
        >
          <Modal.Header closeButton>
            <Modal.Title id="contained-modal-title-vcenter">
              {this.props.data.title}
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <h4> {this.props.data.subTitle} </h4>
            <p>{this.props.data.content}</p>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.props.onHide}>Close</Button>
          </Modal.Footer>
        </Modal>
      </div>
    );
  }
}

export default Article;

我已經在Feed.jsx中將標題設置為打開模式的按鈕。 每個提要在控制台上打開同一文章。 它顯示道具ID未定義。

安慰:

Id: Feed.jsx:22
(2) […]
​
0: Object { _id: "5cf24b53431f5f089496354b", author: "Arjun", title: "Liberalism and Loyality", … }
​
1: Object { _id: "5cf7a4b26332500efc0d1919", author: "Kapil Goel", title: "Made my first website", … }
​
length: 2
​
<prototype>: Array []
 feedData Feed.jsx:23
Warning: Each child in a list should have a unique "key" prop.

Check the render method of `Feed`.for more information.
    in li (at Feed.jsx:29)
    in Feed (at Feeds.jsx:38)
    in div (at Feeds.jsx:37)
    in Feeds (created by Context.Consumer)
    in Route (at App.js:14)
    in div (at App.js:11)
    in App (at src/index.js:10)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:9) index.js:1375
    e index.js:1375
    React 5
    render Feed.jsx:26
    React 13
    componentDidMount Feeds.jsx:19
This is working. Visibility: undefined Article.jsx:10
This is the id of the feed: undefined Article.jsx:11
This is working. Visibility: undefined Article.jsx:10
This is the id of the feed: undefined Article.jsx:11
feedData is Array:  false Feeds.jsx:20
GEThttp://localhost:3000/sockjs-node/432/v3s4dxpn/websocket

我們不能將key關鍵字用作react組件中的自定義prop,因為它已在react中預先保留。

通常, key關鍵字在迭代中用於標識循環中的元素或為循環中的元素提供唯一標識。

您可以使用feedId作為道具,

<Article
  // key={feed.id}
  feedId={feed.id} // you can use feedId instead of key
  show={this.state.showModal}
  onHide={modalClose}
  data={feed}
/>

同樣在Article.jsx ,您正在使用this.props.visible進行控制台,但尚未將其作為道具傳遞。

    axios
  .get("http://localhost:5000/api/items")
  .then(res => res.data)
  .then(data => {
    this.setState({ isLoaded: true, feeds: data });
  })
  .catch(err => console.log("Error !! : " + err));

如果可以console.log數據,然后再將其放入setState。 知道數據是否為數組格式很重要。 您可能無法訪問feeds中Feed組件的“關鍵”屬性的feeds.id,或者可能遇到更大的問題,因為即使Feed組件需要一個數組,也可以為其提供對象

暫無
暫無

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

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