我正在尝试从 api 获取标题和描述 JSON 数据以显示在某个页面上当点击链接进入该页面时,标题和说明会显示 OK。在页面重新加载时出现错误:TypeError:无法读取未定义的属性“标题”。这是我希望数据显示 DataShow.tsx 的地方:import React, { useEffect } from 'react';import { connect } from 'react-redux';import { fetchBook } from '../../actions';export const DataShow: React.FC = (props: any) => { useEffect(() => { async function asyncHook() { const { id } = props.match.params.id; await props.fetchBook(id) return } asyncHook(); }, []); // if (!props.book) { // return <div>Loading...</div> // } return ( <div> <h1>{props.book.title}</h1> <h5>{props.book.description}</h5> </div> </div> );}const mapStateToProps = (state: any, ownProps?: any) => { return { book: state.books[ownProps.match.params.id] }}export default connect(mapStateToProps, { fetchBook })(DataShow);这是我的 axios 函数 fetchBook index.ts:import { FETCH_BOOK } from './types';import books from '../apis/books';export const fetchBook = (id: string) => async (dispatch: any) => { const response = await book.get(`/books/${id}`); dispatch({ type: FETCH_BOOK, payload: response.data })}类型.ts:export const FETCH_BOOK = 'FETCH_BOOK';书籍.ts:import axios from 'axios';export default axios.create({ baseURL: 'http://localhost:3002/api/v1/'});我已经尝试了一些方法,例如“useEffect”钩子中的异步函数,但它不起作用,所以它并没有真正的区别,因为无论是否存在相同的错误,我都会得到相同的错误。我还尝试了一些条件逻辑(如您所见,它已被注释掉)但它只是停留在“正在加载...”,因为 props.stream 显然是未定义的。我确定它与 api 无关,因为我有多个页面,这不是问题。这是页面重新加载时我得到的完整错误:×TypeError: Cannot read property 'title' of undefinedDataShowsrc/components/books/DataShow.tsx:62 61 | <div>> 62 | <h1>{props.book.title}</h1> | ^ 63 | <h5>{props.book.description}</h5> 64 | </div> 65 | </div>当单击链接并转到请求的页面时,即使数据(标题和描述)正确显示,控制台也会显示此错误:GET http://localhost:3002/api/v1/books/undefined 404 (Not Found) xhr.js:178 谢谢
添加回答
举报
0/150
提交
取消