I cannot render the data from my db in React.js project "TypeError: Cannot read property 'title' of undefined"

I cannot render the data from my db in React.js project "TypeError: Cannot read property 'title' of undefined"

我正在使用 Axios 从我的 API 中获取数据,但是当我尝试渲染状态时,我得到一个错误:“TypeError: Cannot read 属性 'title'未定义的。

我对之前的组件使用了相同的代码,它似乎有效。

数据如下所示:

[
{
"portfolio": {
"title": "Portfolio",
"subTitle": "Checkout my works"
},
"cv": {
"title": "Download my cv",
"subTitle": "Aviable in three languages"
},
"contact": {
"title": "Let's talk",
"subTitle": "Send me and e-mail"
},
"_id": "5eff2aefa386601f00c98b7d",
"__v": 0
}
]

App.js 文件中的代码: 我只是使用状态通过投资组合组件传递数据。

<Route path="/portfolio"  render={() => (<Portfolio title={state.header.portfolio.title} subTitle={state.header.portfolio} />)} />

完整代码:

const App = () => {
  const [state,setState] = useState({
    header:[]
  })

  useEffect(() => {
    axios.get('http://localhost:8080/api/metainfo')
    .then(res=>res)
    .then(data=>{
     // console.log(data.data)
   
     setState(prevState=>{
       return{...prevState,header:data.data}
     })
     
    })
  },[]);

  
  return (
    <Router>
      <div className="App">
        <NavBar />

        <div className="app-wrap">
          <Switch>
            <Route path="/" exact render={Home} />
            <Route path="/portfolio"  render={() => (<Portfolio title={state.header.portfolio.title} subTitle={state.header.portfolio} />)} />
            <Route path="/cv" component={CV} />
            <Route path="/contact" component={Contact} />
            <Route path="/footer" component={Footer} />
          </Switch>

        </div>
      </div>
    </Router>
  );
}

错误:Image with errors

请帮忙

您的错误似乎来自组件的初始加载。为了解决这个问题,请更改您的 Portfolio props

<Portfolio title={state.header.length > 0 ? state.header[0].portfolio.title : ''} subTitle={state.header.length > 0 ? state.header[0].portfolio.subTitle : ''} />

首先,我不会创建您自己的 setState,而是将您的状态挂钩更改为:

const [header, setHeader] = useState([]);

也就是说,假设你的数据是一个数组。我不确定为什么它是一个数组,但这就是你提供的。

接下来,您的 useEffect 中有一个不必要的 .then() 行。我会这样改变它:

  useEffect(() => {
    axios.get('http://localhost:8080/api/metainfo')
    .then(res=>{
     // console.log(res.data)
   
     setHeader(res.data)
     // Use [...res.data] if necessary
    })
  },[]);

最后,因为您的 header 状态对象是一个数组,您需要在 Route 中引用它,如下所示:

<Route path="/portfolio"  render={() => (<Portfolio title={header.length > 0 ? header[0].portfolio.title : ''} subTitle={header.length > 0 ? header[0].portfolio.subTitle : ''} />)} />

我已经编辑了我的答案以包含来自 blankart 的答案。