簡體   English   中英

在兩個 React.js 組件之間傳遞一個 JSON 作為 Prop

[英]Pass a JSON as a Prop between two React.js Components

我一直在嘗試傳遞通過在表單提交+用戶輸入后點擊 REST api 獲得的 JSON 對象。 我能夠將獲得的數據傳遞給同一個文件中的另一個組件(第二個組件試圖遍歷 JSON 並將其呈現為 HTML 表)但是當我嘗試對其應用map函數時,它失敗了。 提前致謝。 請在下面找到錯誤和代碼:

錯誤:

TypeError: this.props.rocks.map is not a function

代碼:

import React, {Component} from 'react'
import './App.css'
import axios from 'axios'

class FooBar extends Component {
    constructor(props) {
        super(props);
    }

     render() {
        console.log(this.props.rocks);
        this.props.rocks.map(function (i, j) {
            console.log(i)
        })
        return <h1>HEY</h1>
    }
}

class App extends Component {
    weekDays = ["Sunday", "Monday"]
    meals = ["BreakFast"]

    constructor(props) {
        super(props);
        this.state = {
            recipeList: [],
            selectedRecipes: [],
            fetchedJson: {},
            fooBar: false
        }
  }

  renderTableHeader() {
    return this.meals.map((key, mealIndex) => {
      return <th key={mealIndex}>{key.toUpperCase()}</th>
    })
  }

  componentDidMount() {
    axios.get(`http://localhost:8080/recipe/all`)
        .then(res => {
          this.setState({ recipeList: res.data });
          // todo: line here will work before lines outside the axios.get
        })
  }

  handleChange(event){
    event.preventDefault();
    console.log(event.target.value);
    this.state.selectedRecipes.push(event.target.value);
  }

  renderTableData() {
    return this.weekDays.map(function (day, dayIndex) {
      return (
          <tr key={dayIndex}>
            <td>{day}</td>
              {
                this.meals.map(function (meal, mealIndex) {
                  return (
                      <td key={mealIndex}>
                        {
                          <select key={meal} onChange={this.handleChange.bind(this)}>
                              <option key="blankOption">Choose Item to Cook</option>
                            {
                              this.state.recipeList.map(function (recipe, recipeIndex) {
                                return <option key={recipeIndex}>{recipe}</option>
                              })
                            }
                          </select>
                        }
                      </td>
                  );
                }.bind(this))
              }
          </tr>
      );
    }.bind(this)) // todo: how does bind work
  }

  handleSubmit(event){
      event.preventDefault();
      console.log(this.state.recipeList);
      let url = 'http://localhost:8080/ingredients/?recipes=' + this.state.selectedRecipes.join(',')
    axios.get(url)
        .then(res => {
          console.log(res.data);
          this.setState({
              fetchedJson: res.data,
              fooBar: true
          })
        })
      this.setState({
          selectedRecipes: []
      })
  }

  render() {
      return (
          <div>
              <form onSubmit={this.handleSubmit.bind(this)}>
                  <table id='students' border="1">
                      <tbody>
                      <tr>
                          <td><b>WeekDay</b></td>
                          {
                              this.renderTableHeader()
                          }
                      </tr>
                      {this.renderTableData()}
                      </tbody>
                  </table>
                  <input type="submit" value="Submit"/>

              </form>
              {this.state.fooBar && <FooBar rocks={this.state.fetchedJson}/>}
          </div>
    )
  }
}
export default App

我們只能將 map 函數應用於數組。 但是您在 App 組件中將 fetchedJson 聲明為對象。 首先將對象 {} 更改為數組 []。 接下來檢查 this.props.rocks 是否給數組提供數據。 然后你可以應用地圖功能。

錯誤很明顯。 Map 函數僅適用於數組。我認為您將 props 作為對象類型而不是數組傳遞。這就是它給出錯誤的原因。

第 1 步:將行更改為 fetchedJson: [] 而不是 fetchedJson: {},

第 2 步:還要檢查 res.data 應該是數組類型而不是對象。(' http://localhost:8080/ingredients/?recipes= ')

暫無
暫無

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

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