useState 在被 RouteProps 初始化时不设置状态

Eri*_*k Z 1 typescript reactjs react-router react-hooks

我有一个使用 useState 的组件。状态是使用 RouteComponentProps 中的属性初始化的。当我在浏览器地址栏中输入 url 时它有效,但当 URL 被链接标签更改时无效。有什么不同?当链接标签更改 url 时,如何设置状态?

使用下面的代码并导航到 /test1 从行中显示 test1/test1

{text}/{props.match.params.text}
Run Code Online (Sandbox Code Playgroud)

按“go”链接会将 URL 更改为 /erik,但会显示 test1/erik。为什么?

interface RouteProps {
    text: string | undefined
}

const Test: React.FunctionComponent<RouteComponentProps<RouteProps>> = (props) => {
    const [text, setText] = useState(props.match.params.text || '');

    return (
    <div>
        <h3>{text}/{props.match.params.text}</h3>
        <Link to="/erik">Go</Link>
    </div>
    );
}

const routes = <div>
    <Route path='/:text?' component={ Test } />
</div>;

render(<BrowserRouter basename={process.env.PUBLIC_URL} children={ routes } />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

这是 Stackblitz 中的代码。https://stackblitz.com/edit/react-ts-c7pvsp

App*_*son 5

您传递给的值useState只会被设置一次作为其初始值,之后您提供给它的参数将被忽略。如果您希望在道具更改时更新文本,我建议useEffect改用。它看起来像这样:

useEffect(() => {
    setText(props.match.params.text || '')
}, [ props.match.params.text ]);
Run Code Online (Sandbox Code Playgroud)

您作为第一个参数传递的函数useEffect将根据您作为第二个参数传递的数组中的值是否发生变化而执行。因此,如果 prop 中的文本发生更改,它将执行该函数并使用新值设置状态。