簡體   English   中英

Render 方法應該有一個 return 語句。 通過貓鼬獲取數據

[英]Render method should have a return statement. Fetch data via mongoose

我正在學習 ReactJS、NodeJS、ExpressJS 並構建一個頁面,您可以在其中向提要(通過 API 的 mongoDB 數據庫)提交內容(帖子),刷新頁面后,您會在輸入文本的表單下方看到帖子。

我收到以下錯誤:“無法編譯 ./src/components/this_file.js Line 22:3:您的渲染方法應該有 return 語句 react/require-render-return 搜索關鍵字以了解有關每個錯誤的更多信息。

任何人都可以解釋或提供一篇文章,從中我可以了解我做錯了什么以及如何解決此渲染問題? 因為從我所見,我確實在渲染后有一個 return 語句。

代碼如下:

import React, { useState, useEffect } from "react";
import { Container} from 'react-bootstrap'
import Layout from '../components/layout'
import { Helmet } from 'react-helmet'
import styles from './layout.module.css'
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button'
import Card from 'react-bootstrap/Card'

// SERVICES
import productService from '../services/productService';

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      content: ''
    }
  }

  render() {

    const [feeds, setfeed] = useState(null);

useEffect(() => {
  if(!feeds) {
    getContent();
  }
})


const getContent = async () => {
  let res = await productService.getFeed();
  console.log(res);
  setfeed(res);
}

const renderFeed = feed => {
  return (
        <>
        <Layout>
        <Helmet>
        <title>Feed</title>
        </Helmet>
        <Container>

        <br /><br /><br />
        {/* <h5>Start typing...</h5> */}

        <form id="feed-form" onSubmit={this.handleSubmit.bind(this)} method="POST">

        <Form.Group>

         <Form.Control
            as="textarea"
            rows="10"
            name="feed"
            style={{ backgroundColor: 'gray'}}
            value={this.state.message}
            onChange={this.onMessageChange.bind(this)}
          />
          <Form.Text className="text-muted">
            Post visible after page refresh.
          </Form.Text>
          
        </Form.Group>

          <Button type="submit" style={{ backgroundColor: 'gray', border: 'grey' }}> 
            Submit
          </Button>
          
        </form><br />

        <Card border="dark" text="light" key={feed._id}>
        <Card.Body>
            {feed.content}<br /><br />
          <Card.Text className="text-right">
            <small className="text-muted">{formatDate(feed.date)}</small>
          </Card.Text>
        </Card.Body>
        </Card>
        <br />

        {(feeds && feeds.length > 0) ? (
          feeds.map(feed => renderFeed(feed))
        ) : (
          <p>No feed found</p>
        )}

<div className={styles.backToHome}>
      <a href="/" className="link">
        ← Back to home
      </a>
    </div>
        </Container>
        </Layout>
        </>
  );
}
  }

  onMessageChange(event) {
    this.setState({content: event.target.value})
  }

  handleSubmit(e) {
    e.preventDefault();
  
    fetch('http://localhost:3000/api/feed', {
        method: "POST",
        body: JSON.stringify(this.state),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      }).then(
      (response) => (response.json())
        ).then((response)=> {
      if (response.status === 'success') {
        alert("Message Sent."); 
        this.resetForm()
      } else if(response.status === 'fail') {
        alert("Message failed to send.")
      }
    })
  }
}

function formatDate( string ) {
  var options = { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
  return new Date( string ).toLocaleDateString([], options);
}

export default App;

謝謝🙏

我感謝所有的答案。

這是最終形式 bois:

import React, { useState, useEffect } from "react";
import { Container} from 'react-bootstrap'
import Layout from '../components/layout'
import { Helmet } from 'react-helmet'
import styles from './layout.module.css'
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button'
import Card from 'react-bootstrap/Card'

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      contents: []
    }
  }

  state = {
    hasErrors: false,
    content: {}
  };

  componentDidMount() {
    fetch("http://localhost:3000/api/feed")
      .then(res => res.json())
      .then(res => this.setState({ contents: res }))
      .catch(() => this.setState({ hasErrors: true }));
  }

  render() {

    const { contents } = this.state

  return (
        <>
        <Layout>
        <Helmet>
        <title>Feed</title>
        </Helmet>
        <Container>

        <br /><br /><br />
        {/* <h5>Start typing...</h5> */}

        <form id="feed-form" onSubmit={this.handleSubmit.bind(this)} method="POST">

        <Form.Group>

         <Form.Control
            as="textarea"
            rows="10"
            name="feed"
            style={{ backgroundColor: 'gray'}}
            value={this.state.message}
            onChange={this.onMessageChange.bind(this)}
          />
          <Form.Text className="text-muted">
            Post visible after page refresh.
          </Form.Text>
          
        </Form.Group>

          <Button type="submit" style={{ backgroundColor: 'gray', border: 'grey' }}> 
            Submit
          </Button>
          
        </form><br />

        {contents.map((item, index) => 
       <> <Card border="dark" text="light">
                      
                          <Card.Body>
                              {item.content}<br /><br />
                            <Card.Text className="text-right">
                              <small className="text-muted">{formatDate(item.date)}</small>
                            </Card.Text>
                          </Card.Body>
                      
                        </Card><br/></>
        )}

<div className={styles.backToHome}>
      <a href="/" className="link">
        ← Back to home
      </a>
    </div>
        </Container>
        </Layout>
        </>
  );
}

  onMessageChange(event) {
    this.setState({content: event.target.value})
  }

  handleSubmit(e) {
    e.preventDefault();
  
    fetch('http://localhost:3000/api/feed', {
        method: "POST",
        body: JSON.stringify(this.state),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      }).then(
      (response) => (response.json())
        ).then((response)=> {
      if (response.status === 'success') {
        alert("Message Sent."); 
        this.resetForm()
      } else if(response.status === 'fail') {
        alert("Message failed to send.")
      }
    })
  }
}

function formatDate( string ) {
  var options = { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
  return new Date( string ).toLocaleDateString([], options);
}

export default App;

按預期工作。

在你的渲染方法中返回一些東西......例如。

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      content: ''
    }
  }

  render() {
   return (<renderFeed/>)
}

但是,您的類組件class App extends React.Component正在使用混合的函數組件方法,這是不允許的。 要么將 App 組件重構為一個功能組件,要么使用“經典”生命周期方法。

看起來您的主要問題是您使用了來自基於類的組件和功能組件的方法的混合,我建議先修復這些方法。

例如,這是在基於類的組件中設置狀態的方式:

constructor(props) {
    super(props);
    this.state = {
      content: ''
    };
  }

這就是您在功能組件中設置它的方式。

const [feeds, setfeed] = useState(null);

但是,您可以將兩者結合使用。 您需要決定是需要類組件還是功能組件。

例如,如果您想使用useStateuseEffect掛鈎,則需要將其轉換為功能組件。

這里解釋一下兩者的區別

此外,在 render() 函數內部,您不返回任何內容。

您確實有一個帶有 return 語句的renderFeed函數,但該 return 語句不在 render() 函數的范圍內。

暫無
暫無

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

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