如果全局变量值发生变化,如何强制渲染?

时间:2016-02-10 14:20:20

标签: javascript reactjs

#File 1:
let ticketEnable = false;

export default class SupportTicketMain extends Component {
  constructor () {
    super();
  }
  render () {
    let expandIcon = <DownIcon/>;
    if (this.state.ticketDetailExpanded) {
      expandIcon = <UpIcon/>;
    }
    return (
      <Section className="ticketMain" primary={true}>
        <TicketHeader expanded={ticketEnable}/>
      </Section>
    );
  }
};

export function setTicketEnablement (value) {
    ticketEnable = value;
}


#file 2:

import { setTicketEnablement } from file1;

export default class SupportTicketTabs extends Component {
  constructor () {
    super();
    this.state = {
      ticketDetailExpanded: false
    };

    this._expandClick = this._expandClick.bind(this);
  }

  _expandClick() {
    this.setState({ticketDetailExpanded: !this.state.ticketDetailExpanded});
    setTicketEnablement(this.state.ticketDetailExpanded);
  }

  render () {
    let expandIcon = <DownIcon/>;
    if (this.state.ticketDetailExpanded) {
        expandIcon = <UpIcon/>;
    }

    return (
          <Button className="expander" type="icon" onClick={this._expandClick}>
             {expandIcon}
          </Button>
    );
  }
};

在#file2的supportTicketTabs类中单击按钮将更新#File1中的全局变量,但如果全局变量值发生更改,则SupportTicketMain渲染不会更新!请指导我。

1 个答案:

答案 0 :(得分:0)

ticketEnable应该是传递给SupportTicketMain的道具。包装SupportTicketTabsSupportTicketMain的组件应该将回调作为修改ticketEnabletoggleTicketEnable)的值和ticketEnable的值的道具传递回来}

class Main extends Component {
  constructor (props) {
    super(props);
    this.onToggleTicketEnable = this.onToggleTicketEnable.bind(this);
    this.state = {
      ticketEnabled: false;
    };
  }
  onToggleTicketEnable() {
    this.setState({ ticketEnabled: !this.state.ticketEnabled });
  }
  render () {
    return (
      <App centered={false}>
        <SupportTicketMain ticketEnable={this.ticketEnabled} />
        <SupportTicketTabs onToggleTicketEnable={this.onToggleTicketEnable}/>
      </App>
    );
  }
}