标签: react-hooks

在 React 中使用 onee 方法动态创建和更新相似状态

我正在尝试handleChange对复选框使用单一方法,然后相应地更新它们各自的状态。当我尝试创建动态函数时,调用它的中断。让我知道我在这里做错了什么,可以使用相同的方法更新复选框的检查状态。

失败的功能 -

const handleChange = (event) => {
    const target = event.target;
    const value = target.checked;
    const functionName = `set${target.name}`;
    // console.log(functionName) // functionName = setisItem1 or setisItem2
    functionName(value);
  };
Run Code Online (Sandbox Code Playgroud)

我的沙箱代码 - https://codesandbox.io/s/tender-hooks-guecv?file=/src/App.js[在此处输入链接描述] 1

javascript ecmascript-6 reactjs react-hooks

0
推荐指数
1
解决办法
61
查看次数

在HOC中使用useState / Hooks进行反应会导致错误“只能在函数组件的主体内部调用挂钩”

不允许在高级组件内部使用挂钩吗?当我尝试使用这种简单模式进行操作时,出现错误Invalid hook call. Hooks can only be called inside of the body of a function component.

// App.js
import React, { useState } from 'react';

const WithState = (Component) => {
  const [state, dispatch] = useState(0);
  return () => <Component state={state} dispatch={dispatch} />;
}

const Counter = ({ state }) => {
  return (
    <div style={{ textAlign: 'center', margin: '0 auto'}}>
      {state}
    </div>
  )
}

const CounterWithState = WithState(Counter);

const App = () => {
  return <CounterWithState />;
} …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

-1
推荐指数
1
解决办法
761
查看次数

错误:对象作为 React 子对象无效,React Hook 中的 prop 未返回

我在尝试return ( <div id="info_side">{info}</div> )以下时收到错误。我有一个有效的_onClick功能,info如果我没有{info}在返回中包含任何地方,我可以控制台日志。我怎样才能解决这个问题?

这是错误: Error: Objects are not valid as a React child (found: object with keys {type, _vectorTileFeature, properties, layer, source, state}). If you meant to render a collection of children, use an array instead.

更新 必须将对象转换为数组,然后映射键值,现在它可以工作了。

const _onClick = event => {
  const display = event.features;
  if (display.length > 0) {
    setInfo(display[0].properties)
  }
}

var list = Object.entries(info).map(([key,value]) => {
  return (
    <div><span className="bold">{key}</span>: <span>{value.toString()}</span></div>
  )
});

return …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

-1
推荐指数
1
解决办法
805
查看次数

我想我拼错了一个道具,但我不确定

所以基本上,我尝试在我的项目中实现 React Hooks,但它给了我这个错误。也许我是盲人,看不到问题所在,我想我拼错了一些东西。但也许我传递了错误的道具,我现在有点困惑。

这是我的标志是组件:

   const SignIn = ({ emailSignInStart, googleSignInStart }) => {
  const [userCredentials, setCredentials] = useState({
    email: '',
    passowrd: ''
  });
  const { email, password } = userCredentials;

  const handleSubmit = async e => {
    e.preventDefault();

    emailSignInStart(email, password);
  };

  const handleChange = e => {
    const { value, name } = e.target;
    setCredentials({ ...userCredentials, [name]: value });
  };

  return (
    <div className='sign-in'>
      <h2>I already have an account</h2>
      <span>Sign in with your email and passowrd</span>

      <form onSubmit={handleSubmit}>
        <FormInput
          name='email' …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

-1
推荐指数
1
解决办法
39
查看次数

React Hook useEffect 缺少依赖项:'props.match.params.id'

我已经创建了一个 React 应用程序。对于数据获取,我使用了 axios。我的应用程序按预期工作正常。但是在我的终端中,我收到了这样的警告Line 34:6: React Hook useEffect has a missing dependency: 'props.match.params.id'. Either include it or remove the dependency array react-hooks/exhaustive-deps。我不想使用// eslint-disable-next-line react-hooks/exhaustive-deps. 有什么替代解决方案吗?

  useEffect(() => {
    axios
      .get("http://localhost:5000/students/" + props.match.params.id)
      .then(response => {
        setState({
          name: response.data.name,
          birthday: response.data.birthday,
          address: response.data.address,
          zipcode: response.data.zipcode,
          city: response.data.city,
          phone: response.data.phone,
          email: response.data.email
        });
      })
      .catch(function(error) {
        console.log(error);
      });

  }, []);
Run Code Online (Sandbox Code Playgroud)

axios react-hooks use-effect

-1
推荐指数
1
解决办法
899
查看次数

在 setState React 钩子之后调用函数

请帮帮我,
我需要像这样在 setState 之后调用一个函数,所以doSomeFunction()只有在设置状态后才能工作

function sth() {
    setState(something)
    doSomeFunction()
}
Run Code Online (Sandbox Code Playgroud)

不使用 useEffect

javascript reactjs react-hooks

-1
推荐指数
1
解决办法
2493
查看次数

Reactjs 中的 setState 不是函数

我是新来的反应,我试图使用 APIfetchsetState状态变量命中 API ,但它抛出错误为

Unhandled Rejection (TypeError): Object(...) is not a function
Run Code Online (Sandbox Code Playgroud)

这是代码-> CodeSandboxLink

import React from "react";
import { useState, useEffect, setState } from "react";
import "./styles.css";

export default function App() {
  const [person, setPerson] = useState([]);
  fetch("https://jsonplaceholder.typicode.com/users")
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      setState(data);
    });
  console.log("dasdasd", person);
  return <div className="App">{JSON.stringify(person)}</div>;
}
Run Code Online (Sandbox Code Playgroud)

请建议我哪里做错了。

javascript fetch setstate reactjs react-hooks

-1
推荐指数
1
解决办法
73
查看次数

为什么我的 try catch 块不会执行?- 反应

我有一个注册模式,有 3 个步骤。

填写信息、获取激活码和成功消息。

我希望当用户填写输入并单击提交按钮时,如果没有错误,则移动到下一步,但如果有错误,则会React Toastify显示消息。

我的问题是为什么try catch阻止MyComponent不起作用?

PS:我正在使用FormikYup

http服务

const handleExpectedError = (response: any) => {
  if (response?.status >= 400 && response?.status < 500) {
    const errors = response?.data?.errors;
    const errPropertyName: string[] = Object.keys(errors);
    toast.error(errors?.[errPropertyName?.[0]]?.[0]);
  }
};

export const handleRegister = async (user: User): Promise<void> => {
  try {
    await axios.post(`${config.apiEndPoint}/auth/register`, user, header);
  } catch ({ response }) {
    handleExpectedError(response);
  }
};
Run Code Online (Sandbox Code Playgroud)

我的组件

  const [step, setStep] = useState(1);
  const formik …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs next.js react-hooks

-1
推荐指数
1
解决办法
1418
查看次数

is it possible in React useState(&lt;&gt;&lt;/&gt;) has initial state is empty div or component?

my code is like that

const [component, setComponent ] = useState( ? )
Run Code Online (Sandbox Code Playgroud)

What will be the initial value for component

if(true)
  setComponent(<ComponentA />)
else
  setComponent(<ComponentB />)
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

-2
推荐指数
1
解决办法
47
查看次数