【问题标题】:How to use the Context API to pass one state & function to multiple different components?如何使用 Context API 将一种状态和功能传递给多个不同的组件?
【发布时间】:2019-02-01 16:22:15
【问题描述】:

我在 React 上工作了 6 个月。我现在才在这个问题上苦苦挣扎,因为 Context API 对我来说很新。我喜欢它,但我不知道如何正确使用它,清理和优化我的 React APP。

我有这个问题,我在每个组件中使用 Axios 获取数据,每个组件具有相同的功能和相同的状态。

我实际上是在复制粘贴.. 来访问我的数据,但我想用 Context API 解决这个问题。

希望有人可以帮助我,我想变得更好并了解这里的 Context API。

我的代码:

state = {
    social_media: [],
    page_home: [],
    loading: true,
};

getCoffee() {
    return new Promise(resolve => {
        setTimeout(() => resolve('☕'), 2000); // it takes half of a second to make coffee
    });
}

async showData() {
    try {
        const wpSocial = axios(`${ACF_DATA_URL}/options/social_media_data`);
        const wpHome = axios(`${WP_DATA_URL}/pages?slug=home`);

        await this.getCoffee();

        await Promise.all([wpSocial, wpHome]).then(response => {
            this.setState({
                social_media: response[0].data.social_media_data,
                page_home: response[1].data[0],
                loading: false,
            });
        });
    } catch (e) {
        console.error(e); // ????
    }
}

componentDidMount() {
    this.showData();
}

我想要完成的是我想创建一个上下文 API 并将相同的状态、函数 ShowData 和 GetCoffee() 传递给多个不同的组件。

我该怎么做?

谢谢大家!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    很简单,先创建一个新的上下文(context.js)

    const Context = React.createContext();
    

    使用上面创建的上下文(context.js)创建提供者,提供者类将保存状态和方法。

    class Provider extends React.Component {
      state = {
        some_state: 'value',
        some_method: this.method
      }
    
      method = () => {
        console.log('It works');
      }
    
      render() {
        return (
          <Context.Provider>
            {this.props.children}
          </Context.Provider>
        );
      }
    }
    

    同时导出提供者和消费者 (context.js)

    const Consumer = Context.Consumer;
    export { Provider, Consumer };
    

    使用提供者 (app.js) 包装 App 组件,以便 App 树下的每个 JSX 组件都可以使用 some_statesome_method

    import { Provider } from './{some_path}/context';
    
    <Provider>
      <App> ... </App>
    </Provider>
    

    最后,消费某个组件中的值,你必须在声明&lt;Consumer&gt;组件后告诉你想要哪些状态属性(这里我们同时使用some_statesome_method

    import { Consumer } from './{some_path}/context';
    
    class SomeComponent extends React.Component {
      render() {
        return (
          <Consumer>
            {({some_state, some_method}) => {
              <button onClick={some_method}>{some_state}</button>
            }
          </Consumer>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 2021-02-28
      • 2019-06-10
      • 2017-11-17
      • 2017-11-07
      • 2016-12-05
      相关资源
      最近更新 更多