使用 ReactRouter withRouter 不适用于 React Hook

Using ReactRouter withRouter doesn't work with a React Hook

我似乎无法在功能组件内部使用 React Hook useState,该功能组件包装在 React Router 的 withRouter 函数调用中。

我需要 withRouter 调用来从浏览器获取 URL 参数。

function TheComponent(props) {
    const { id } = props.match.params;
    // this is returning null for both done & setDone
    const {done, setDone} = useState(false);

    // some code that's using id

    return <div>
       // some tags here
    </div>
}

export default withRouter(function(props) {
     return <TheComponent {...props} {...this}  />
});

添加 withRouter 似乎会阻止 Hook 工作。

我该如何解决这个问题?

我尝试在函数调用中添加 Hook,但没有成功:

export default withRouter(function(props) {
     const {done, setDone} = useState(false);
     return <TheComponent {...props} {...this} done={done} setDone={setDone}  />
});

我想我需要了解的主要事情是 Hooks 的局限性是什么?似乎不能在 withRouter HOC 函数中声明它们。那是对的吗?我该如何解决这个问题,因为我需要使用我需要 withRouter 函数的 URL 参数。

您忘记为您的组件添加参数:

function TheComponent(props) {
    const { id } = props.match.params;
    // this is returning null for both done & setDone
    const {done, setDone} = useState(false);

    // some code that's using id

    return <div>
       // some tags here
    </div>
}

您对 useState 函数使用了错误的语法 returns。您应该使用方括号而不是大括号。

来自 React docs 的 useState:

const [fruit, setFruit] = useState('banana');

When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0] and 1 to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.

编辑:正如其他人所说,您还应该将 props 值作为参数传递给您的函数。

你的代码的主要问题是你没有在 TheComponent 的构造函数中获取道具,但如果它违反了钩子规则,你可以使用其他方法。

const TheComponent = (match) => {
        //you can destruct from props direct on parameters if you want
        const { id } = match.params;
        const [done, setDone] = useState(false);

        return <div>
           // some tags here
        </div>
    }

    export const WrapperComponent = withRouter((props) => {
      //you can destruct from props direct on parameters if you want
      const { match } = props;
      return <TheComponent match={match} />
    });