简体   繁体   English

如何更新按钮单击时useEffect()挂钩的值

[英]how update the value of useEffect() hook on button click

I have a functional component and I have created a button inside it. 我有一个功能组件,我在其中创建了一个按钮。 I am also using a "Use_effect()" hook. 我也在使用“Use_effect()”钩子。 My main is to re-render the functional component, update the use_effect() hook when the button is clicked. 我的主要是重新渲染功能组件,在单击按钮时更新use_effect()钩子。

const Emp_list = (props) => {
  useEffect(() => {
    props.getList(props.state.emp);
  }, []);

    return (

      <div>
        {props.state.emp.map((val ) =>   
               {val.feature_code}
               {val.group_code}
    <button onClick = {() => props.removeEmpFromList(val.feature_code)} > Remove </button>

        <EmpForm empList={props.state.emp} 
                    onChangeText = {props.onChangeText}
                   />
        </div>

        <button onClick=  {() => props.getdata (props.state)}>Get Names</button>
        <p> 
      </div>

    );

  };

export default Emp_list;
    removeEmpFromList = (i) => { 
      const remaining = this.state.emp( c => c.feature_code !== i)
      this.setState({
      emp: [...remaining]

        })

      }

When I click the Remove button , it will basically remove the employee from the list. 当我单击“删除”按钮时,它基本上会从列表中删除该员工。 The function removeEmpFromList will update the state. 函数removeEmpFromList将更新状态。 The functional component EmpForm basically shows the list of all employees. 功能组件EmpForm基本上显示了所有员工的列表。

So I want to re-render the page so that, it updates the state value in useEffect() hook. 所以我想重新渲染页面,以便更新useEffect()钩子中的状态值。 So when EmpForm is called again on re-rending it shows the updated list. 因此,当再次调用EmpForm时,它会显示更新的列表。

You didn't provide the code for removeEmpFromList() ... but probably it updates the state by mutation therefor component gets the same object ref - compared shallowly - no difference, no reason to rerender. 你没有提供removeEmpFromList()的代码......但可能它通过变异更新状态组件得到相同的对象ref - 比较浅 - 没有区别,没有理由重新渲染。

Modify removeEmpFromList() method to create a new object for emp - fe using .filter . 修改removeEmpFromList()方法,使用.filteremp -fe创建一个新对象。

If not above then passing entire state is the source of problem (the same reason as above). 如果不在上面,则通过整个state是问题的根源(与上述相同的原因)。

Simply pass only emp as prop or use functions in setState() (to return a new object for the entire state) this way . 只需通过仅emp作为道具或使用功能setState()返回一个新的对象为整个州) 这种方式

I figured it out! 我想到了! Thanks for the help guys. 谢谢你的帮助。 So, it was not re-rendering because initally, useEffect() second parameter was [] , if you change it to props.state then it will update the changes made to the state and re-render the component automatically. 因此,它不是重新渲染,因为最初,useEffect()第二个参数是[],如果将其更改为props.state,则它将更新对状态所做的更改并自动重新呈现组件。

  useEffect(() => {
    props.getList(props.state.emp);
  }, [props.state.emp]);


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM