状态改变时再次调用函数

时间:2020-02-12 22:10:51

标签: javascript reactjs state

我具有以下功能:

  const getCurrentCharacters = () => {
    let result;
    let characters; 

    if(selectedMovie !== 'default'){
      characters = state.data.filter(movie => movie.title === selectedMovie)[0].characterConnection.characters;
      result = characters; 
    }else if(selectedSpecies !== 'default'){
      const currentSpecies = characters.filter(char => char.species.name === selectedSpecies || char.species === selectedSpecies);
      result = currentSpecies; 
    }else if (selectedPlanets !== 'default'){
      const currentPlanets = characters.filter(char => char.homeworld.name === selectedPlanets); 
      result = currentPlanets; 
    }else{
      return []; 
    }   

    return result; 
  }

它利用useState钩子:

  const [selectedSpecies, setSelectedSpecies] = useState("default");
  const [selectedPlanets, setSelectedPlanets] = useState("default");
  const [selectedMovie, setSelectedMovie] = useState("default");

只要其中任何一个更新,我都想发挥作用。您能否提供有关如何执行此操作的基本示例。只要我能弄清楚每当发生更改时如何调用该函数,我自己就能弄清楚其余部分,上下文就不重要了。

1 个答案:

答案 0 :(得分:2)

在这种情况下,如果要在特定状态更改上触发任何功能,则有一个名为useEffect的钩子。您可以使用该设置运行副作用。阅读文档:

效果挂钩可让您在功能组件中执行副作用。

让我给你举个例子:

const [selectedMovie, setSelectedMovie] = useState('default');

// ... other states, code part

useEffect(() => {
   console.log('selectedMovie has been changed');

   // ... here you can implement your logic for state changes
   // ... like that function call
}, [selectedMovie]);

建议阅读:Using the Effect Hook

希望对您有帮助!