React Prop没有价值,无法控制台日志

时间:2019-05-10 01:52:44

标签: javascript reactjs api

我正在尝试以道具的形式将API数据传递给App.js。我可以控制台记录API数据,这样我就知道它来了。当我将其分配给道具时,尽管我得到ResultList.js:28未被捕获(在承诺中) TypeError:this.props.openState不是函数。这是正确的语法吗?抱歉,如果这是一个幼稚的问题,我对这一切都是陌生的。

我曾尝试用几种不同的方式分配它,但是我对道具的不熟悉逐渐成为障碍。我知道API正在返回数据,因为我可以通过控制台注销该数据。

````import { Helmet } from "react-helmet";
````import zipcodes from "zipcodes";
````import SearchBar from "../../components/SearchBar/SearchBar";
````import ResultsDisplay from "../../components/ResultDisplay/ResultDisplay";
````import Nav from "../../components/Nav/Nav"
````import API from "../../API";
````import Footer from "../../components/Footer/Footer";
````import "./ResultsList.css";

````class ResultList extends React.Component {
    ````state = {
        ````openState: [],
        ````proPublica: []
    ````}
    ````onSearchSubmit = zipcode => {
        ````const data = zipcodes.lookup(zipcode);
        ````const state = data.state;
        ````const lat = data.latitude.toFixed(2);
        ````const lon = data.longitude.toFixed(2);

        ````const openStateQuery = "lat=" + lat + "&long=" + lon;

        ````API.getOpenStateData("api/v1/legislators/geo/?" + ````openStateQuery).then(OSresponse => {

            ````this.props.openState(OSresponse.data)//making the data a prop so ````we can pass it to app.js
            ````console.log("OSresponse:", OSresponse.data);
            ````console.log(this.props.openState)
        });
    }

   ```` render() {
       ```` return (
           ```` <div>
               ```` <Helmet>
                   ```` <style>{'body { background-color: #f0f0f0;}'}</style>
                ````</Helmet>
                ````<Nav />
                ````<SearchBar
                    ````onSubmit={this.onSearchSubmit}
                    ````placeholder="Enter a zip code..."
                ````/>
                ````<div className="container">
                    ````<div className="results-container">
                        ````I removed this divs content for sake of brevity
                  ````  </div>
                ````</div>
                ````<Footer />
            ````</div>
        ````)
    ````}
````}

````export default ResultList;
I would expect the same response as 
console.log("OSresponse:", OSresponse.data);

2 个答案:

答案 0 :(得分:0)

您实际上并没有提供足够的详细信息或代码来找出问题所在,但听起来您尚未将正确的道具传递给此react组件。您需要将功能从App.js传递到此文件,作为名为openState的道具

例如

// App.js
openState = (data) => {
  // do something with the data
  this.setState({ data })
}

render() {
  return <MyComponent openState={this.openState} />
}

答案 1 :(得分:0)

您得到的错误TypeError: this.props.openState is not a function.仅是由于此行引起的,

this.props.openState(OSresponse.data)

这意味着您正在尝试从父组件访问功能,而您的情况根本不存在。相反,这是您的父组件,您需要将数据从该组件传递到子组件。

您应该将数据设置为来自API响应的状态,

this.setState({openState:OSresponse.data})

现在您可以将数据传递到子组件的了,

<AnyComponent openState={this.state.openState} />

在您AnyComponent中,现在您可以像这样使用数据了,

this.props.openState

Also see