POST 方法:错误:钩子调用无效。 Hooks 只能在函数组件内部调用

时间:2021-07-01 11:24:16

标签: react-native react-hooks use-effect

我想在按下 TouchableOpacity 时从 API 发出一条消息提醒。我有一个单一的函数处理座椅预订和单个函数调用座椅预订函数来获取消息。 这是我的代码

const generalBooking = (seat, uid, vid, tc_id) => {
    const [msg, setMsg] = useState(0);
    useEffect(() => {
      (async () => {
        const response = await fetch(
          `http://192.168.8.100/dbops/actions/make_booking.php?seat=${seat}&uid=${uid}&vid=${vid}&tc_id=${tc_id}`
        );
        const result = await response.json();
        setMsg(result.message);
        // alert(result.message);
      })();
    }, []);

    return msg;
  };

function seat1Booking(seat1, uid, vid, tc_id) {
    const msg = generalBooking(1, uid, vid, tc_id);
    Alert.alert(msg);
  }

return (
    <Screen style={{ paddingBottom: 5 }}>
          {/* Seat 1 starts */}
          <TouchableOpacity style={styles.seat} onPress={seat1Booking}>
            <MaterialCommunityIcons name="seat" size={40} color={seat1Color} />
            <Button title="1" style={{ width: 20 }} color={seat1Color} />
          </TouchableOpacity>
          {/* Seat 1 ends */}
    </Screen>
)

当我在 console.log(seat1booking()) 之外记录它时,generalBooking 和个人座位 1Booking 函数工作正常,但是当我将它传递给 TouchableOpacity 时,它会发出警告

1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
....

我曾尝试阅读许多链接 Error Invalid hook call. Hooks can only be called inside of the body of a function componentHow to fix React(TypeScrtipt) error "Invalid hook call."?,包括错误消息中提供的链接,但都徒劳无功。

问题可能是对处理座位预订的单个函数的函数调用,例如 Seat1Booking 还是 generalBooking 函数?请指教

2 个答案:

答案 0 :(得分:0)

您不能在函数调用中使用 useEffect,在这种情况下您也不需要。

const generalBooking = async (seat, uid, vid, tc_id) => {
  const response = await fetch(
    `http://192.168.8.100/dbops/actions/make_booking.php?seat=${seat}&uid=${uid}&vid=${vid}&tc_id=${tc_id}`
  );
  const result = await response.json();

  return result.message;
};

const seat1Booking = async (seat1, uid, vid, tc_id) => {
  const msg = generalBooking(1, uid, vid, tc_id);
  Alert.alert(msg);
}


答案 1 :(得分:0)

我设法找到了这个问题的解决方案,在这里,

const generalBooking = async (seat, uid, vid, tc_id) => {
    // const [msg, setMsg] = useState(0);
    const response = await fetch(
      `http://192.168.8.100/dbops/actions/make_booking.php?seat=${seat}&uid=${uid}&vid=${vid}&tc_id=${tc_id}`
    );
    const result = await response.json();
    // setMsg(result.message);
    Alert.alert("Booking Status", result.message);
  };

  useEffect(() => {
    return () => {
      seatBooking(seat, uid, vid, tc_id);
    };
  }, []);

const seat1Booking = (seat, uid, vid, tc_id) => {
    seatBooking(1, uid, vid, tc_id);
  };

感谢@Hazout 的提示,因为它指导了我的搜索。