Stop the communication between react components using mufa after a condition

巧了我就是萌 提交于 2019-12-01 21:21:48
Eric Levine

It looks like mufa has a way to unsubscribe like this:

const mufa = new Mufa();
const {on, fire, unsub} = mufa;
class Input extends React.Component {
   
   onChange(event) {
     fire('input_change', event.target.value);
   }

   render() {
     return <input onChange={this.onChange.bind(this)} />
   }
}

class Label extends React.Component {
   state= {text: ""};
   constructor(props) {
        super(props);
        this.sub = null;
   }
   componentDidMount() {
     this.sub = on('input_change', this.onInputChange.bind(this));
 
   }

   onInputChange(inputValue) {

      if(inputValue.length >= 10) {
       unsub(this.sub);
       return;
      };

      this.setState({text: inputValue});
      // I need code to stop calling this method when inputValue reaches 10 characters. 
       
    }

   render() {
     return <label > {this.state.text} </label>
   }
}

class App extends React.Component {
   // No logic here thanks to the Sub/Pub pattern. 
   render() {
     return (
        <div>
           <Label />
           <Input/>
    
        </div>
     )
   }
}


ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://abdennour.github.io/mufa/mufa-latest.min.js"></script>


<div id="app" ></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!