【问题标题】:Patch request in functional component react功能组件中的补丁请求反应
【发布时间】:2022-07-23 01:44:29
【问题描述】:

有一个称为切换的功能组件,需要添加一个补丁请求,因此每次切换触发时,更改都会在 UI 和数据库中更新(显示/隐藏)。 唯一的办法是使用hoots useState吗?

这里有一些代码供参考

const ToggleStats = ({ label, value, onChange }) => {
  const toggled = !!value


  const handleToggle = () => {
    onChange(!toggled)
    // TODO when the toggle gets clicked a request gets send to update the bd (show/hide)
    api.patch(`admin/admin/institutions/id/?with_deleted=true`, { body })
      .then(res => res.json())
      .then(data => {
        this.setState({ })
      })
  }

  return (
    <Toggle
      label={label}
      labelPosition='left'
      labelStyle={styles.label}
      iconStyle={styles.ripple}
      thumbSwitchedStyle={styles.toggle}
      trackSwitchedStyle={styles.toggleBackround}
      onToggle={handleToggle}
    />
  )
}

ToggleStats.propTypes = {
  label: PropTypes.string.isRequired,
  value: PropTypes.any,
  onChange: PropTypes.func.isRequired
}

任何帮助将不胜感激。

【问题讨论】:

  • 尝试向handleToggle(x) 函数添加参数。如果您担心使用 useState,请查看您是否处于开启/关闭状态。

标签: reactjs json api react-hooks patch


【解决方案1】:

你的问题有点不清楚,但我猜你只是想使用 useState 来管理显示或隐藏。

const Switch = ({isOn, handleToggle}) => {
  return (
    <>
      <input
        checked={isOn}
        onChange={handleToggle}
        className="react-switch-checkbox"
        id={`react-switch-new`}
        type="checkbox"
      />
      <label className="react-switch-label" htmlFor={`react-switch-new`}>
        <span className={`react-switch-button`} />
      </label>
    </>
  )
}

function App() {
  const [show, setshow] = React.useState(false)
  return (
    <div>
      <div className="app">
        <Switch isOn={show} handleToggle={() => setshow(!show)} />
      </div>
      {show ? 'Toggled' : null}
    </div>
  )
}

在我的示例中,您可以看到我通过使用反应钩子 useState 来管理父应用程序组件中的显示状态。单击切换现在将显示设置为真或假,我现在可以使用该状态来运行逻辑,在我的例子中是一个三元运算符,它显示文本“在屏幕上切换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2021-05-10
    • 2014-04-20
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多