gpt4 book ai didi

javascript - 如何在react-router v5中使用history.push传递对象?

转载 作者:行者123 更新时间:2023-12-02 22:13:43 25 4
gpt4 key购买 nike

如何在/start-sound 上播放声音并在/stop-sound 上停止声音?

/开始声音

const history = useHistory();

const startSound = () => {
const sound = new Audio("test.mp3");
sound.play();
history.push("/stop-sound", [sound]);
}

/停止声音

const stopSound = () => {
sound.pause();
sound.currentTime = 0;
}

此代码将在浏览器中显示错误。

 DataCloneError: Failed to execute 'pushState' on 'History': An object could not be cloned.

<小时/>
history.push("/stop-sound", [sound]);

此样式将遵循 React Router 文档。

React Router | history

而且我不知道如何将声音对象与/stop-sound 一起使用。

<小时/>

另一个例子

demo

/pass-text

const PassTextPage = () => {
const history = useHistory();

const passText= () => {
history.push({
pathname: "/view-text",
state: { name: "Hello" }
});
};

return <button onClick={passText}>pass</button>;
};

/ View 文本

const ViewTextPage = () => {
const text = props.location.state.name; // 'props' is not defined.

const viewText = () => {
console.log(text);
};

return <button onClick={viewText}>view</button>;
};

App.jsx

const App = () => (
<BrowserRouter>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/pass-text">
<PassTextPage />
</Route>
<Route exact path="/view-text">
<ViewTextPage />
</Route>
</BrowserRouter>
);

最佳答案

将属性传递给导航组件的方式

history.push({
pathname: '/stop-sound',
state: { name: 'Hello'}
});

在导航组件中像这样访问。

如果它是无状态组件

let location = useLocation();

location.state.name

如果基于类的组件

 this.props.location.state.name

关于javascript - 如何在react-router v5中使用history.push传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59466150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com