reactjs事件监听器beforeunload已添加但未删除

时间:2016-08-23 06:47:43

标签: javascript reactjs addeventlistener event-listener

我有一个反应组件,如:

import React, { PropTypes, Component } from 'react'


class MyComponent extends Component {

    componentDidMount() {
       window.addEventListener("beforeunload", function (event) {
            console.log("hellooww")
            event.returnValue = "Hellooww"
        })
    }

    componentWillUnmount() {
        window.removeEventListener("beforeunload", function (event) {
            console.log("hellooww")
            event.returnValue = "Hellooww"
        })
    }

    render() {

        return (
            <div>
                Some content
            </div>
        )
    }

}

export default MyComponent

此处将事件列表器添加到组件中。当我刷新页面时,它会弹出要求离开页面。

但是当我转到另一个页面然后刷新它再次显示相同的弹出窗口时。

我要从eventListener上的组件中删除componentWillUnmount。那么为什么它没有被删除?

如何删除其他页面上的beforeunload事件?

3 个答案:

答案 0 :(得分:45)

removeEventListener应该获得对addEventListener中分配的相同回调的引用。重新创建功能是行不通的。解决方案是在其他地方创建回调(在此示例中为onUnload),并将其作为对addEventListenerremoveEventListener的引用传递:

import React, { PropTypes, Component } from 'react'


class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.onUnload = this.onUnload.bind(this); // if you need to bind callback to this
    }

    onUnload(event) { // the method that will be used for both add and remove event
        console.log("hellooww")
        event.returnValue = "Hellooww"
    }

    componentDidMount() {
       window.addEventListener("beforeunload", this.onUnload)
    }

    componentWillUnmount() {
        window.removeEventListener("beforeunload", this.onUnload)
    }

    render() {

        return (
            <div>
                Some content
            </div>
        )
    }

}

export default MyComponent

答案 1 :(得分:1)

Ori的解决方案对我不起作用。我必须这样做才能使它工作......(谢谢你的文档)

@Controller
public class PetApiController implements PetApi {

@Autowired
GenerateResponse generateResponse;
...
  public ResponseEntity<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId,
    @ApiParam(value = "Additional data to pass to server") @RequestPart(value="additionalMetadata", required=false)  String additionalMetadata,
      @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) {
      return generateResponse.uploadFile(petId, additionalMetadata, file);
  }
...
}

答案 2 :(得分:0)

您可以使用以下钩子:

https://www.npmjs.com/package/react-beforeunload

示例:

import { Beforeunload } from 'react-beforeunload';

// ...

<Beforeunload onBeforeunload={(event) => event.preventDefault()}>
  <MyApp />
</Beforeunload>