不能在React上的箭头函数内的函数中设置State

时间:2018-03-31 22:46:23

标签: javascript reactjs arrow-functions

我试图在箭头功能的函数内使用This。如何在我的函数中使用setState

showDeleteConfirm = commentId => {
    const { deleteComment } = this.props;
    const { comments } = this.state;
    // this exist
    confirm({
      title: 'Are you sure delete this?',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        // this is undefined
        deleteComment(commentId);
        const targetPosition = _.findIndex(comments, item => {
          return item._id === commentId;
        });
        if (targetPosition !== -1) {
          // this is undefined
          console.log(this.state.comments);
          this.setState(prevState => ({
            comments: [
              ...prevState.comments.slice(0, targetPosition),
              ...prevState.comments.slice(targetPosition + 1)
            ]
          }));
        }
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };

2 个答案:

答案 0 :(得分:1)

您不能,箭头函数中的this始终与其周围区域中的this相同。只需使用常规功能即可。

const showDeleteConfirm = function(commentId) {

答案 1 :(得分:1)

你在箭头函数中得到this就好了(method =()=> {}),尽管鼓励使用类中的方法(method(){})。您面临的问题不是使用箭头功能,而是您在何处以及如何调用它。代码的第一部分可以正常工作,因为您可以立即调用它。鉴于onOKonCancel位于showDeleteConfirm的上下文之后,onOKonOK更为重要,而showDeleteConfirm's定义了showDeleteConfirm = commentId => { const { deleteComment } = this.props; const { comments } = this.state; confirm({ title: 'Are you sure delete this?', okText: 'Yes', okType: 'danger', cancelText: 'No', onOk: this.onDeleteConfirm.bind(this, commentId), onCancel: this.onDeleteCancel.bind(this) }); }; onDeleteConfirm = (commentId) => { const { comments } = this.state; const targetPosition = comments.findIndex(item => item._id === commentId); this.props.deleteComment(commentId); if (targetPosition !== -1) { this.setState(prevState => ({ comments: [ ...prevState.comments.slice(0, targetPosition), ...prevState.comments.slice(targetPosition + 1) ] })); } } onDeleteCancel = () => {} 。当然this将使用它自己执行,而不是onDeleteConfirm。这是一种解决方法:

onDeleteCancel

我们将 cartesian .doOnCompleted(() -> { System.out.println(" DOC#1 # ELEMENTS IN CACHE " + cache.size()); }) .filter((CartesianProduct cp) -> !cache.containsKey(cp.fromTo)) .groupBy((cp) -> cp.from) .subscribe((group) -> { GeoLocation from = (GeoLocation) ((GroupedObservable)group).getKey(); //Google Maps API allows max 25 Destinations per call ((GroupedObservable)group).window(25) .doOnCompleted(() -> { System.out.println(" DOC#2 # ELEMENTS IN CACHE " + cache.size()); }) .subscribe((window) -> { ((rx.subjects.UnicastSubject)window).asObservable().toList() .observeOn(Schedulers.from(httpExecutor)) .doOnCompleted(() -> { System.out.println(" DOC#3 # ELEMENTS IN CACHE " + cache.size()); }) .subscribe( (list) -> { //Call Google Maps API here List<CartesianProduct> toList = (List<CartesianProduct>) list; List<GeoLocation> targets = new ArrayList(); for (CartesianProduct cP : toList) { targets.add(cP.to); } GoogleMapsClientWrapper.getDistanceAndDurationForDirection(from, targets, cache); }); }); }); System.out.println(" # ELEMENTS IN CACHE " + cache.size()); 绑定到constructor(props) { super(props); this.state = { animationValue: new Animated.Value(0) }; } <Animated.View style={{ flex: 0.15, backgroundColor: `rgba(0,0,0,${background}` }} onPress={this.removeBackground} > <Text style={[{ textAlign: 'right' }>{hometeam.result} - {awayteam.result}</Text> </Animated.View> background,所以当它们最终被执行时,它们会正确地得到它们。你可以在这里阅读abound bind:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind