【问题标题】:Const method getting called on render in functional component在功能组件中渲染时调用 Const 方法
【发布时间】:2020-05-13 01:39:59
【问题描述】:
const App = props=> {
  const handleAdition=(abc)=>{
    console.log('called');
   props.dispatch({
     'type':'create',
     'payload':abc
   });
 }
  return (
    <div className="App">
    <AddB handleAdition={handleAdition}/>
    </div>
  );
}

const AddB=props=> {
  let [name, setName] = useState('');
  return (
    <div className="header">
      <div className="form">
      <label for='name'>Name</label>
      <input onChange={e=>setName(e.target.value)}type='text' name='name'/>
      </div>
      <button onClick={props.handleAdition({name})}> Add</button>
    </div>
  );
}

该方法被无限调用,直到堆栈已满。程序失败。我是功能组件的新手。我究竟做错了什么?

【问题讨论】:

  • 没有&lt;AddB /&gt;组件的代码图片不完整
  • 添加了它,它实际上被调用了一次,props.dispatch 重新渲染组件,这样持续循环

标签: reactjs redux react-redux react-functional-component


【解决方案1】:

改变这个

&lt;button onClick={props.handleAdition({name})}&gt; Add&lt;/button&gt;

&lt;button onClick={() =&gt; props.handleAdition({name})}&gt; Add&lt;/button&gt;....

这是因为 onClick 需要一个函数...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2020-08-02
    • 2022-11-16
    相关资源
    最近更新 更多