reactjs 我想在React.js上创建一个条件并使用axios进行发布

p1tboqfb  于 2022-12-22  发布在  React
关注(0)|答案(3)|浏览(114)

在下面的API文件数据中,

    • 如果"brightness_value"大于0,我想将模式设置为"turn_on"。**
    • 如果亮度值为0,我想将模式设置为"turn_off"。**

这有可能实现吗?
如果是,如何做到?

    • API文件**
Method: POST
URL: xxx.com
Data:

{
"time_start":"16:20",
"time_end":"16:21",
    "mode":{
        "mode":"turn_off", //or “turn_on”
        "rgb_color":[255,255,255],
        "brightness":50
    }
}
    • 我的React.js代码**
const [brightness_value, setBrightnessValue] = useState();

  const setSchedule = async(data) => {
    await axios.post('xxx.com',
      {
        time_start: "16:20",
        time_end: "16:21",
        mode: {
          mode: "turn_off", 
          rgb_color: [255,255,255], 
          brightness: brightness_value,
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Scheduled!');   
      })
      .catch(err => {
        console.log(err);
        console.log('Missed Schedule!');
      });
  }
1wnzp6jl

1wnzp6jl1#

使用三元运算符执行以下操作:

mode: {
         mode: brightness_value === 0 ? "turn_off":"turn_on",  
          rgb_color: [255,255,255], 
          brightness: brightness_value,
        }
9udxz4iz

9udxz4iz2#

只需在此处添加条件

time_start: "16:20",
        time_end: "16:21",
        mode: {
          mode: brightness_value === 0 ? "turn_off":"turn_on", 
          ....
xfb7svmp

xfb7svmp3#

mode: {
         mode: Number.parseInt(brightness_value) === 0 ? "turn_off":"turn_on",  
          rgb_color: [255,255,255], 
          brightness: brightness_value,
        }

它应该能完成任务。

相关问题