【问题标题】:my return function does not work inside function in react hooks我的返回函数在反应钩子中的函数内部不起作用
【发布时间】:2019-07-24 12:28:59
【问题描述】:

我的返回函数在函数内部不起作用,请帮我解决这个问题。

import React from 'react';
import axios from 'axios';

    const Category = () => {
        //const[data, useData]=useState([]);
        const FuncMen =() =>{
            var e = document.getElementById("menid");
            var country = e.options[e.selectedIndex].value;
            if(country === "T-shirt"){
                axios.post('http://localhost:8011/api/social/finddatamen',{country})
                .then((res) => {

                     var men = res.data.res.filter(filtereddata => filtereddata.category === "tshirt" ) 
                        console.log('selected value is',men);

                            men &&men.map((val,i)=>{

                            console.log("Tshirtt:",val.Tshirt,"Price:",val.price);
                            return(
                                <div key={i}>
                                    <h1>hello</h1>
                                  {val.Tshirt},
                                  {val.price}
                                  </div>
                            )
                        })


                        })
                    .catch((error) => {
                    console.log('error block called',error);
                })

            }

【问题讨论】:

  • 请给出解决方案

标签: node.js reactjs mongodb react-hooks


【解决方案1】:

您需要在.then 块之外、.catch 之后返回 JSX (div, h1)。

【讨论】:

    【解决方案2】:

    我不知道您为什么将 FuncMen 嵌套在 Category 中。如果你想使用钩子,我会删除 FuncMen 并使用类似的东西..

    import React, {useState} from 'react';
    import axios from 'axios';
    
    const Category =() =>{
        const [category, setCategory] = useState(undefined)
        var e = document.getElementById("menid");
        var country = e.options[e.selectedIndex].value;
        if(country === "T-shirt"){
            axios.post('http://localhost:8011/api/social/finddatamen'{country})
                .then((res) => {
                    var men = res.data.res.filter(filtereddatafiltereddata.category=== "tshirt" ) 
                    console.log('selected value is',men);
                    setCategory(men)
    
                .catch((error) => {
                    console.log('error block called',error);
                            })
                }
        }
        return (
            <div>
                <h1>hello {category}</h1>
            </div>
            )
                )
    }
    

    然后在其他一些组件中,使用它:

    render() {
        return (<Category />)
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2020-08-22
      • 2020-06-19
      • 2018-05-21
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      相关资源
      最近更新 更多