【问题标题】:setState via ref not working inside useEffect?通过 ref 设置状态在 useEffect 中不起作用?
【发布时间】:2020-06-28 15:45:44
【问题描述】:

我正在尝试使用 useRef 即清除反应表组件的 filtered 状态。 ref.current.setState({...})。 这是我的组件中的一个 sn-p:

const Customers = (props) => {
  const customerTableRef = useRef()

  useEffect(() => {
    const customerTable = customerTableRef.current
    if (customerTable) {
      customerTable.setState({ ...customerTable.state, filtered: [] })
      console.log("table effect::", customerTable.state)
    }
  }, [props.selectedDealer])

我在 UI 中有一个选择输入,它绑定到 props.selectedDealer 我想在用户更改 props.selectedDealer 时清除反应表的过滤器。 react table 组件在Customers 组件中不可用,但在层次结构中处于非常低的级别:

Customers > CustomersTable > AppTableWrapper > AppTable > ReactTable.

我将customerTableRef 传递给ReactTable。在开发工具中,我可以看到 ref 被组件选项夸大了,但 customerTable.setState({ ...customerTable.state, filtered: []}) 并没有改变 ReactTable 的状态。

【问题讨论】:

    标签: reactjs react-hooks react-ref react-effects


    【解决方案1】:

    我建议将 customerTable 传递给 redux。在我们通过 redux 将其传递给您的组件之后。 在状态变量中:useState 或 useReducer。状态变量的更新将导致组件的重新渲染。 In a ref: 相当于类组件中的实例变量。改变 .current 属性不会导致重新渲染

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2021-03-26
      • 2020-06-20
      • 2018-12-09
      • 2020-08-26
      • 2021-08-30
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      相关资源
      最近更新 更多