好的,所以我加載根網址。應該呈現一個帖子串列,而不是我得到了臭名昭著的 React 錯誤......
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
index.js 和 app.js 似乎可以正確呈現。我相信故障出在 PostList 組件中,也許是渲染方法?我知道解決方案可能很簡單,但我看不到它。
索引.js
7
8 ReactDOM.render(
9 <React.StrictMode>
10 <HashRouter>
11 <App />
12 </HashRouter>
13 </React.StrictMode>,
14 document.getElementById('root')
15 );
16
17
18
19
20 reportWebVitals();
應用程式.js
8
9 class App extends React.Component {
10
11 constructor() {
12 super();
13 this.state = {
14 posts: []
15 };
16 }
17
18 componentDidMount() {}
19
20 render() {
21 return (
22 <div className="container">
23 <h1>hello world</h1>
24 <Routes>
25 <Route exact path='/' element={PostList} />
26 <Route path='/post/:id' element={Post} />
27 </Routes>
28 </div>
29 );
30 }
31 }
32
33 export default App;
后串列.js
5
6 class Post extends React.Component {
7 constructor() {
8 super();
9 this.state = {
10 title: '',
11 content: ''
12 };
13 }
14
15 componentDidMount() {
16 let api = new Api();
17
18 api.posts(this.props.match.params.id).then(data => {
19 this.setState({
20 title: data.title.rendered,
21 content: data.content.rendered
22 });
23 });
24 }
25
26 render() {
27 let post = this.state;
28 return (
29 <div className='row'>
30 <h3>{post.title}</h3>
31 <div dangerouslySetInnerHTML={{__html: post.content}} />
32 </div>
33 );
34 }
35 }
36
37 class PostList extends React.Component {
38 constructor() {
39 super();
40 this.state = {
41 posts: []
42 };
43 }
44
45 componentDidMount() {
46 let api = new Api();
47
48 api.posts().then(data => {
49 this.setState({
50 posts: data
51 });
52 });
53 }
54
55 render() {
56 let posts = this.state.posts.map((post, index) =>
57 <h3 key={index}>
58 <Link to={`/post/${post.id}`}>{post.title.rendered}</Link>
59 </h3>
60 );
61
62 return (
63 <div>{posts}</div>
64 );
65 }
66 }
67
68 export {Post, PostList}
uj5u.com熱心網友回復:
顯然您在配置路由時遇到了問題
你可以在 React Router https://reactrouter.com/docs/en/v6/getting-started/overview的檔案中查看配置路由的部分
嘗試替換 app.js 檔案中第 25 和 26 行的 PostList 和 Post,如下所示
<Route exact path='/' element={<PostList/>} />
<Route path='/post/:id' element={<Post/>} />
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403745.html
標籤:
