Javascript 为什么window.location在我的react组件中不起作用?
堆栈溢出: 我遇到了一个非常奇怪的问题,下面是我的示例代码:Javascript 为什么window.location在我的react组件中不起作用?,javascript,reactjs,Javascript,Reactjs,堆栈溢出: 我遇到了一个非常奇怪的问题,下面是我的示例代码: export default class MyAwesomeComponent extends React.Component{ constructor(props){ super(props) this.handleClick = this.handleClick.bind(this) } handleClick(){ //do some expression
export default class MyAwesomeComponent extends React.Component{
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
//do some expression
window.location = 'url I want to jump'
}
render(){
return <button onClick={this.handleClick}/>
}
}
看来我遇到了js单线程问题,setTimeout
或nextTick
可以解决这个问题
你能解释一下吗
顺便说一句,运行环境是在一个定制的MVC下,带有react-like、redux-like包。也许是MVC内部的黑魔法而不是单线程造成了我的麻烦
thx这本身不是一个很好的答案,只是为了举例说明。
无论您使用的是什么服务器环境,您的代码都应该运行良好,因为
window.location
在客户端运行
类MyAwesomeComponent扩展React.Component{
建造师(道具){
超级(道具)
this.handleClick=this.handleClick.bind(this)
}
handleClick(){
//表达
window.location=https://google.com'
}
render(){
返回单击
}
}
ReactDOM.render(,document.getElementById('root'))代码>
您想用window.location
实现什么?实际上,它是一个注销模块。它将打开注销页面,这是一个验证URL非常感谢。您的代码可能表明我的MVC有问题,但与react无关
handleClick(){
setTimeout(()=>{window.location = 'url I want to jump'})
}