首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >setState通过ref不能在useEffect中工作吗?

setState通过ref不能在useEffect中工作吗?
EN

Stack Overflow用户
提问于 2020-03-17 22:32:21
回答 1查看 117关注 0票数 0

我正在尝试使用useRef viz清除react表组件的filtered状态。ref.current.setState({...})。这是我的组件中的一段代码:

代码语言:javascript
复制
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的select输入,每当用户更改props.selectedDealer时,我想清除react表的过滤器。react表组件在Customers组件中不可用,但在层次结构中处于非常低的级别:

Customers > CustomersTable > AppTableWrapper > AppTable > ReactTable

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

EN

回答 1

Stack Overflow用户

发布于 2020-03-17 22:50:02

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60724458

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档