【问题标题】:Error withRef is removed. To access the wrapped instance, use a ref on the connected component when using Redux Form错误 withRef 已删除。要访问包装的实例,请在使用 Redux Form 时在连接的组件上使用 ref
【发布时间】:2019-05-10 00:37:36
【问题描述】:

我第一次尝试让 Redux Form 工作,但出现以下错误:

Invariant Violation withRef 被移除。访问包装的 例如,在连接的组件上使用 ref。

我做错了什么?我一写(从示例中复制/粘贴)商店,就会抛出错误。

这里是代码。

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'

const rootReducer = combineReducers({
  form: formReducer
})

const store = createStore(rootReducer);


function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我还制作了一个代码沙箱来显示问题:https://codesandbox.io/s/07xzolv60

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    虽然上述方法确实有效,但如果您想使用最新的,您需要做的就是将您的类组件重构为一个函数组件。查找withRef() API。 (请将此作为正确答案投票以帮助其他开发人员。)

    https://redux-form.com/7.1.2/docs/api/fieldarray.md/#props-you-can-pass-to-code-fieldarray-code-

    【讨论】:

    • 请将此答案投票为正确答案,以免开发人员最终降级以使其正常工作!
    • 你是怎么做到的?你能编辑我的小提琴吗?
    • 代替class Something extends React.Component {},试试const Something = (props) =&gt; {}
    • @ClaytonRay 您的最后评论与您的​​答案不一致。你说all you need to do is refactor your function component to a class component.你的意思是从类组件重构为函数组件?
    • 我看到了混乱。我不记得这个问题,但我确定我的意思是从类重构为函数。无论哪种方式,您都应该能够使用类或函数组件,因为两者都可以使用 refs。
    【解决方案2】:

    我遇到了同样的问题,显然 redux-formreact-redux 版本大于 6 时无法正常工作。

    对我来说,将 react-redux 包降级到版本 5 有帮助:

    npm install react-redux@5.1.1 --save
    

    【讨论】:

    • 这真的是一个解决方案吗?
    【解决方案3】:

    我不建议降级react-redux,而是说您将两个库都更新到最新版本,问题应该得到解决。请参阅有关从 v6 迁移到 v8 的 Redux Form 文档。

    https://redux-form.com/8.2.2/docs/MigrationGuide.md

    【讨论】:

      【解决方案4】:

      https://github.com/reduxjs/react-redux/releases/tag/v6.0.0

      连接的 withRef 选项已替换为 forwardRef

      export default 
        connect(
          mapStateToProps,
          mapDispatchToProps, null, {forwardRef: true})(Component)
      

      【讨论】:

        【解决方案5】:

        只需更新到最新版本的 redux-form (8.1.0)。无需降级。

        【讨论】:

          猜你喜欢
          • 2019-05-18
          • 2018-01-03
          • 2021-08-03
          • 1970-01-01
          • 2023-03-30
          • 2020-02-26
          • 2018-03-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多