我正在學習反應。我正在嘗試使用包含外部檔案setState的功能,但它沒有設定狀態。每次重繪 頁面時它都顯示為空。componentDidMount()Array of Data
應用程式.js
import './App.css';
import React from 'react';
import newData from './data.js';
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
data : []
}
}
componentDidMount() {
this.setState({data: newData});
console.log(this.state.data)
}
render(){
return (
<div>Hello</div>
)
}
}
資料.js
const newData = [
{
"id": 1,
"name": "GoodName",
},
]
export default newData
我還嘗試通過更改資料格式并包裝成 aa Seed.functionlike
window.Seed = (function() {
const newData = [
{
id: 1,
name: 'GoodName',
},
];
return {newData: newData };
}());
并試圖setState通過
this.setState({data: Seed.newData});
但它說,Seed is not defined
我是否需要匯入外部 json 陣列檔案
index.html而不是 App.js?在設定狀態之前,我是否需要使用
map函式或for of回圈來迭代資料中的每個元素?
我已經嘗試了很多次,但它仍然無法正常作業。
任何幫助將非常感激。先感謝您。
uj5u.com熱心網友回復:
this.state.data呼叫后不是立即可用的setState。檢查:
https ://reactjs.org/docs/faq-state.html#why-doesnt-react-update-thisstate-synchronously
嘗試堅持查看陣列的內容console.log。render
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/476259.html
標籤:javascript 反应
下一篇:沒有表單的AJAX發布功能未重置
