react有类似vue中的watch方法吗?truffle遇坑
发布于 5 年前 作者 jowang2016 3767 次浏览 来自 问答

具体场景是这样的: 需要在react中使用drizzle app.js必须要等待drizzle加载完成才能render,不知道该怎样控制加载,目前代码是这样的:

class App extends Component {
  state = { loading: true, drizzleState: null };

  componentDidMount() {
    const { drizzle } = this.props;

    // subscribe to changes in the store, keep state up-to-date
    this.unsubscribe = drizzle.store.subscribe(() => {
      const drizzleState = drizzle.store.getState();
      if (drizzleState.drizzleStatus.initialized) {
        this.setState({ loading: false, drizzleState });
      }
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    // wait for drizzle to be initialized before showing app
    if (this.state.loading) return "Loading Drizzle...";
    return (
      <div className="App">
        <ReadValue
          drizzle={this.props.drizzle}
          drizzleState={this.state.drizzleState}
        />
        <SetValue
          drizzle={this.props.drizzle}
          drizzleState={this.state.drizzleState}
        />
      </div>
    );
  }
}

这样写的话 页面就会停留在加载阶段 不会往下执行了 所以怎样才能等drizzle加载之后 再render呢? react有类似vue中的watch方法吗?

3 回复

这个库我没有用过。 你期望dizzle加载完重渲染的话。在加载完成后将this.setState({loading:true}),应该能满足你的需求吧。

看代码, state.loading 不就是在控制加载完成前不渲染吗

drizzle.store.subscribe会在加载完调用回调吗? 测了一下,drizzle.store.subscribe里的回调没有被调用过

回到顶部