从自定义钩子返回 JSX

时间:2021-04-21 17:06:03

标签: reactjs

我对 React 还很陌生,我在使用 JSX 时遇到了问题。我试图制作一个自定义钩子,以便它返回 JSX。这个想法是一个有错误的模态将在钩子中显示和处理,所以它不需要在每个使用钩子的组件中。我有以下几点:

 import {useCallback, useState} from 'react';
 
 const useHttp = (requestObj, setData) => 
 {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [elements, setElements] = useState(null);
    
    const sendRequest = useCallback(() =>
    {
        setIsLoading(true);
        setError(null);
        fetch(requestObj.url)
            .then(res => res.json())
            .then(data => {
                setIsLoading(false);
                setData(data);
                let jsx = (<div>Testing conor</div>)
                setElements(jsx);
            })
            .catch(err => 
            {
                setError(err.message);
                setIsLoading(false);
                console.log('There was an error');
            });
    }, []);
 
    return {
        isLoading: isLoading,
        error: error,
        elements: elements,
        sendRequest: sendRequest
    }
} 
 
export default useHttp;
 

当我尝试运行项目时,我进入了控制台:

Uncaught Error: Module parse failed: Unexpected token (18:27)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|                 setIsLoading(false);
|                 setData(data);
>                 let jsx = (<div>Testing conor</div>)
|                 setElements(jsx);
|             })
    at eval (useHttp.js:1)
    at Object../src/hooks/useHttp.js (main.c31b3f1b1129869704a7.bundle.js:2391)
    at __webpack_require__ (main.c31b3f1b1129869704a7.bundle.js:2425)
    at eval (OwnerSearch.tsx:14)
    at Object../src/components/OwnerSearch/OwnerSearch.tsx (main.c31b3f1b1129869704a7.bundle.js:2348)
    at __webpack_require__ (main.c31b3f1b1129869704a7.bundle.js:2425)
    at eval (App.tsx:11)
    at Object../src/App.tsx (main.c31b3f1b1129869704a7.bundle.js:2326)
    at __webpack_require__ (main.c31b3f1b1129869704a7.bundle.js:2425)
    at eval (index.tsx:10)

谁能告诉我 a.) 如果我能做到这一点,b.) 如果能,那怎么做?

谢谢

webpack 配置

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    entry: "./src/index.tsx",
    target: "web",
    mode: "development",
    output: {
        filename: "[name].[chunkhash].bundle.js",
        path: path.resolve(__dirname, "../dist"),
    },
    resolve: {
        modules: ["src", "node_modules"],
        extensions: [
            ".tsx",
            ".ts",
            ".js",
            ".jsx",
            ".svg",
            ".css",
            ".json",
            ".mdx",
            ".png"
        ],
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, "css-loader"],
            },
            {
                test: /\.s[ac]ss$/i,
                use: [
                  // Creates `style` nodes from JS strings
                  "style-loader",
                  // Translates CSS into CommonJS
                  "css-loader",
                  // Compiles Sass to CSS
                  "sass-loader",
                ],
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [
                  {
                    loader: 'file-loader',
                    options: {
                        name: '/public/icons/[name].[ext]'
                      }
                  },
                ],
              },

        ],
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            title: "Spectrum App",
            template: __dirname + "/public/index.html",
            inject: "body",
            filename: "index.html",
        }),
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css",
        }),
    ]
};

1 个答案:

答案 0 :(得分:-1)

你的问题与返回部分有关,所以如果你在那里返回一个数组,它不会引起任何问题。

此外,我建议您查看有关自定义钩子的 React 文档。 https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook

import { useCallback, useState } from 'react'
   const useHttp = (requestObj, setData) => {
   const [isLoading, setIsLoading] = useState(false)
   const [error, setError] = useState(null)
   const [elements, setElements] = useState(null)

   const sendRequest = useCallback(() => {
      setIsLoading(true)
      setError(null)
      fetch(requestObj.url)
     .then((res) => res.json())
     .then((data) => {
     setIsLoading(false)
     setData(data)
     let jsx = <div>Testing conor</div>
     setElements(jsx)
    })
      .catch((err) => {
      setError(err.message)
      setIsLoading(false)
      console.log('There was an error')
      })
   }, [])

 return [isLoading, error, elements, sendRequest]
 }