簡體   English   中英

嘗試將獲取的json數據映射到React應用時,“狀態”未定義

[英]“State” undefined when trying to map fetched json data into React app

我正在從wordpress api獲取數據。 登錄控制台時,我看到了數據數組。 在映射數據時,出現錯誤消息“#myStateName.map不是函數”。

我已經去過ReactJS.org,CSS Tricks甚至Stack Overflow來尋找解決方案,但是似乎什么都沒有用

class WPHome extends Component {

  constructor(props) {
super(props);
this.state = {
  error: null,
  isLoaded: false,
  details: []
};
  }

  componentDidMount() {
fetch(API_URL)
  .then(res => res.json())
  .then(
    (result) => {
      console.log(result['0'])
      this.setState({
        isLoaded: true,
        details: [result]
      });
    },
    // Note: it's important to handle errors here
    // instead of a catch() block so that we don't swallow
    // exceptions from actual bugs in components.
    (error) => {
      this.setState({
        isLoaded: true,
        error
      });
    }

  )
}

render() {
const { error, isLoaded, details } = this.state;
if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading...</div>;
} else {
  return (
    <div>
      {details.map(item => (
        <div key={item.id}>
          <p>{item.id}</p>
          <div>
            <img src={item._embedded['wp:featuredmedia']['0'].source_url} alt={item.id} />
          </div>
          <p>{item.content}</p>
          <hr />
        </div>
      ))}
    </div>
  );
}
  }

我希望我的數據傳遞到HTML塊中,但會拋出錯誤

您不會在您的狀態中初始化details 在這里添加:

this.state = {
  error: null,
  isLoaded: false,
  result: [],
  details: [] // <- missing initialization
};

在構造函數的狀態聲明中,添加以下內容

 this.state = {
  details:[],
  error: null,
  isLoaded: false,
  result: []
 }

該錯誤可能是由於this.state.details在開始時未定義而引起的。

我還注意到,對於您的提取請求,您正在執行以下操作。

  this.setState({
    isLoaded: true,
    details: result['0']
  });

由於result是一個數組,因此不應將其設置為details狀態,如下所示。

  this.setState({
    isLoaded: true,
    details: result
  });

似乎您沒有在狀態中聲明details變量。

您可以嘗試運行:

render (
   <div>
          {
            details.map(item => (
             <div key={item.id}>
              <p>{item.status}</p>
             </div>
         }
   </div>
);

然后發布如何?

請使用以下setState語句,因為您的結果是一個對象

this.setState({ isLoaded: true, details: [result] });

要遍歷對象,請參考以下鏈接-https://jsfiddle.net/oek6um0h/1/

{Object.keys(details).length && Object.keys(details).map((item,k) => {
return <any></any>
}) || <p>nothing found</p>}

map是用於數組而不是對象使用map,我們需要使用Object.keys() ,該方法返回給定對象自己的可枚舉屬性名稱的數組,其順序與正常循環中獲得的順序相同

我終於弄明白了。 雖然必須使用Axios,但它確實有效。

  constructor(props) {
super(props);
this.state = {
  error: null,
  isLoaded: false,
  details: []
};
}

componentDidMount(){
axios
  .get(API_URL)
  .then(response => response.data.map(detail => ({
    image: `${detail._embedded['wp:featuredmedia']['0'].source_url}`,
      content: `${detail.content.rendered}`,
      id: `${detail.id}`
    }))
  )
  .then(details => {
    this.setState({
      details,
      isLoading: false
    });
  })
  .catch(error => this.setState({ error, isLoading: false }));
}


render() {
const { isLoading, details } = this.state;

return (
  <React.Fragment>
      {!isLoading ? (
        details.map(detail => {
          const { id, content, image } = detail;
          return (
            <div key={id}>
              <p>{content}</p>
              <div>
                <img src={image} alt={id} />
              </div>
              <p>{content}</p>
              <hr />
            </div>
          );
        })
      ) : (
          <p>Loading</p>
      )
      }
  </React.Fragment>
)
  }

您需要使用默認值而不是resultconstructor定義details

constructor(props) {
    super(props);
    this.state = {
        error: null,
        isLoaded: false,
        details: [] // define missing
    };
}

暫無
暫無

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

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