反应功能组件在一定条件下从上下文调用其他函数或调用方法

时间:2020-04-07 06:24:38

标签: reactjs react-native

我在下面的功能组件内部调用函数时遇到问题 state.locations.length自动增加,我想知道是否达到4(> 3) 我可以在上下文中调用函数来重置它

因为我已经 useEffect 用于其他功能,所以不能使用它。

如果在我在下面标记代码的位置内怎么办

  const TrackListScreen = ({ navigation }) => {
    const { 
      state, 
      addLocation, 
      fillTrackData, 
      saveTrack,
    } = useContext(LocationContext);  


    const sendTrackAuto = async () => {
      console.log('sendTrackAuto running')
    };

    return <Container>
      <Text h3>{ state.locations.length }</Text>

      // how do I call function sendTrackAuto or saveTrack context 
      // here is what I want 
      // if state.locations.length > 3 then I want call sendTrackAuto or saveTrack automatically without using button keypress

      // below is the one that I think but I don't think it's correct
      { (state.locations.length > 3) ? sendTrackAuto : null }
    </Container>;
  };

1 个答案:

答案 0 :(得分:0)

使用useEffect钩子在依赖项数组中使用state.locations.length产生副作用。当长度值更新时,效果开始运行。

Conditionally firing an effect

const TrackListScreen = ({ navigation }) => {
  const { 
    state, 
    addLocation, 
    fillTrackData, 
    saveTrack,
  } = useContext(LocationContext);  

  const sendTrackAuto = async () => {
    console.log('sendTrackAuto running')
  };

  useEffect(() => {
    if (state.locations.length > 3) {
      sendTrackAuto();
      // or do anything else
    }
  }, [state.locations.length]);

  return (
    <Container>
      <Text h3>{ state.locations.length }</Text>
    </Container>
  );
};