如果其中任何一個為空,我想讓位置或/和傳感器型別的請求過濾器選項回傳一個空字串。
我正在使用選擇下拉選單來更改 filter.location 和 filter.sensorType 的值
預期輸出:
- 如果 filter.location 為 null 但 filter.sensorType 不為 null
request = ...farms?sensortype=abc&page=3 - 如果 filter.location 不為 null 但 filter.sensorType 為 null
request = ...farms?location=abc&page=3 - 如果兩者都為空
requests = ...farms?page=3
我目前的結果:
...farms?location=abc&undefined&page=3
const [filter, setFilter] = useState({
sensorType: null,
location: null,
});
// API REQUEST
const {
data
} = await axios.get(
`http://localhost:8080/api/farms?${
filter.location && `location=${filter.location}`
}${filter.sensorType && `&sensorType=${filter.sensorType}`}&page=${page}`
);
uj5u.com熱心網友回復:
只需使用三元條件運算子:
condition ? resultIfTruthy : resultIfFalsy
const [filter, setFilter] = useState({
sensorType: null,
location: null,
});
// API REQUEST
const {
data
} = await axios.get(
`http://localhost:8080/api/farms?${
filter.location ? `location=${filter.location}` : ''
}${filter.sensorType ? `&sensorType=${filter.sensorType : ''}`}&page=${page}`
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421934.html
標籤:
上一篇:試圖點擊元素
