Reactjs 从自定义挂钩返回JSX

Reactjs 从自定义挂钩返回JSX,reactjs,Reactjs,我还没有反应过来,我对钩子中的JSX有一个问题。我正在尝试创建一个自定义钩子,以便它返回JSX。其思想是,带有错误的模态将在钩子中显示和处理,因此它不需要出现在使用钩子的每个组件中。我有以下资料: import {useCallback, useState} from 'react'; const useHttp = (requestObj, setData) => { const [isLoading, setIsLoading] = useState(false);

我还没有反应过来,我对钩子中的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;
 

您的问题与返回部分有关,因此如果您在那里返回一个数组,它不会导致任何问题

我还建议您查看关于定制挂钩的React文档。

从“react”导入{useCallback,useState}
const useHttp=(requestObj,setData)=>{
常量[isLoading,setIsLoading]=useState(false)
const[error,setError]=useState(null)
常量[elements,setElements]=useState(null)
const sendRequest=useCallback(()=>{
setIsLoading(真)
设置错误(空)
获取(requestObj.url)
.然后((res)=>res.json())
。然后((数据)=>{
setIsLoading(错误)
setData(数据)
设jsx=测试conor
集合元素(jsx)
})
.catch((错误)=>{
设置错误(错误消息)
setIsLoading(错误)
console.log('发生错误')
})
}, [])
返回[isLoading,error,elements,sendRequest]
}

听起来好像您没有在
.js
文件中将webpack配置为传输JSX语法。你用的是什么运输工具,巴贝尔?请显示它的配置。JSX语法在其他文件中正常工作吗?我注意到堆栈跟踪包括
.tsx
文件。如果希望这是一个带有jsx的typescript文件,则必须将文件命名为
.tsx
.ts
不起作用)
.js
可能会工作,但正如Bergi指出的,这取决于您的transpiler配置。@NicholasTower我的文件是.tsx。@discodowney错误消息说它在
.js
文件(
。/src/hooks/useHttp.js
)上失败。您是否有两个同名文件,一个
.js
一个
.tsx
?不,这不是问题所在。
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)
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",
        }),
    ]
};
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]
 }