【问题标题】:How to call same api with different params on click of button in react native如何在 React Native 中单击按钮时调用具有不同参数的相同 api
【发布时间】:2022-01-13 23:44:19
【问题描述】:

我制作了 3 个不同的自定义按钮:

<TouchableOpacity onPress={selectClosed}>
    <Text>Closed</Text>
</TouchableOpacity>

<TouchableOpacity onPress={selectPending}>
    <Text>Pending</Text>
</TouchableOpacity>

<TouchableOpacity onPress={selectComplete}>
    <Text>Complete</Text>
</TouchableOpacity>

及其 onPress 函数:

const selectClosed = () => {
    getShiftDetails.bind(null, 'closed');
};
const selectPending = () => {
    getShiftDetails.bind(null, 'pending');
};
const selectComplete = () => {
    getShiftDetails.bind(null, 'complete');
};

以下是我的 api 调用方式:

const getShiftDetails = useCallback(
    (
        page = 1,
        limit = 20,
        mode: 'pending' | 'complete' | 'closed' = 'complete',
    ) => {
            const payload = {
                page,
                limit,
                status: [mode],
            };
            ApiFunctions.post(apiUrl + '/shift', payload)
                .then(
                    // other stuff
                )
                .catch((err: any) => {
                    // other stuff
                });
    },
    [user],
);

默认情况下,我的 api 调用是使用 modecomplete 完成的。现在,如果我单击pending 按钮,则应使用mode 作为pending 进行另一个api 调用。但这并没有发生。我不确定我哪里出错了。

【问题讨论】:

  • getShiftDetails 需要 三个 参数,mode第三个。当你绑定它时,我相信你给出的参数是作为 first 参数提供给绑定函数的参数。但在这种情况下,第一个参数是page。尝试将 mode 参数移到第一位 (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
  • 你也用错了.bind。应该改为const selectClosed = getShiftDetails.bind(null, 1, 20, 'closed');。见.bind()

标签: javascript reactjs typescript react-native api


【解决方案1】:

我建议使用 customHooks。 (更改选项时,再次进行呼叫。)

const useFetch = (url, options) => {
  const [response, setResponse] = React.useState(null);

  React.useEffect(async() => {
    const res = await fetch(url, options);
    const json = await res.json();

    setResponse(json);
  }, [options]);

  return response;
};

使用钩子:

const payload = {
  page = 1,
  limit = 20,
  status: 'pending',
};

const { response } = useFetch("url", payload) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多