父级状态发生改变后,ReactJS子组件不会更新

时间:2019-11-25 03:41:40

标签: reactjs

我有一个组件,单击按钮后,该函数将更新状态(顺序),该状态将重新呈现组件,但仅更新跨度的文本。是否也应该重新渲染“ i标签”?

const {useState, useEffect} = React;

const SortType = {
  UNSORTERED: { icon: 'fas fa-sort', next: 'ASCENDING' },
  ASCENDING: { icon: 'fas fa-sort-up', next: 'DESCENDING' },
  DESCENDING: { icon: 'fas fa-sort-down', next: 'UNSORTERED' }
}

const Sorter = ({ trigger, sortOrder }) => {
  const [order, setOrder] = useState(SortType.UNSORTERED)

  function onSort() {
    const nSortOrder = SortType[order.next]
    setOrder(nSortOrder)
    trigger(nSortOrder)
  }

  useEffect(() => {
    if (sortOrder) {
      setOrder(sortOrder)
    }
  }, [sortOrder])

  return (
    <button onClick={onSort}>
      <i className={order.icon}/>
      <span>{order.icon}</span>
    </button>
  )
}

ReactDOM.render(
  <Sorter trigger={console.log} sortOrder={SortType.UNSORTERED} />,
  document.getElementById("react")
);
<script src="https://use.fontawesome.com/releases/v5.11.2/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

实际结果与预期结果

Actual result Expected result

1 个答案:

答案 0 :(得分:1)

我认为问题出在您的 font-awesome的CDN链接。因为正如我们所看到的,order.icon的值确实发生了变化,所以i标记的className发生了变化,但是随后它使用“ fa-sort”类保持不变,从而呈现了奇怪的svg组件。只需替换为fontawesome here的另一个cdn链接,它就可以正常工作。

  • 从您的代码中替换一行代码后,代码即可正常工作:

const {useState, useEffect} = React;

const SortType = {
  UNSORTERED: { icon: 'fas fa-sort', next: 'ASCENDING' },
  ASCENDING: { icon: 'fas fa-sort-up', next: 'DESCENDING' },
  DESCENDING: { icon: 'fas fa-sort-down', next: 'UNSORTERED' }
}

const Sorter = ({ trigger, sortOrder }) => {
  const [order, setOrder] = useState(SortType.UNSORTERED)

  function onSort() {
    const nSortOrder = SortType[order.next]
    setOrder(nSortOrder)
    trigger(nSortOrder)
  }

  useEffect(() => {
    if (sortOrder) {
      setOrder(sortOrder)
    }
  }, [sortOrder])

  return (
    <button onClick={onSort}>
      <i className={order.icon}></i>
      <span>{order.icon}</span>
    </button>
  )
}

ReactDOM.render(
  <Sorter trigger={console.log} sortOrder={SortType.UNSORTERED} />,
  document.getElementById("react")
);
<!-- REPLACED HERE -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css"> 

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>