前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >怎样使用React Context API [每日前端夜话0x26]

怎样使用React Context API [每日前端夜话0x26]

作者头像
疯狂的技术宅
发布2019-03-27 10:51:42
8960
发布2019-03-27 10:51:42
举报
文章被收录于专栏:京程一灯京程一灯

每日前端夜话0x26

每日前端夜话,陪你聊前端。

每天晚上18:00准时推送。

正文共:5730 字 1 图

预计阅读时间: 15 分钟

翻译:疯狂的技术宅 原文:https://www.toptal.com/react/react-context-api

React Context API 【https://reactjs.org/docs/context.html】现在已经成为一个实验性功能,但是只有在 React 16.3.0 【https://reactjs.org/blog/2018/03/29/react-v-16-3.html】中才能用在生产中。本文将向你展示两个基本的 Web 商店应用程序,一个使用了 Context API 进行构建,另一个则不用。

这个新的API解决了一个严重的问题 ——prop drilling。 即使你不熟悉这个术语,如果你曾经用 React.js 做过开发,它可能就已经在你身上发生过了。 Prop drilling 是通过将数据传递到多个中间 React 组件层,将数据从组件A 获取到组件 Z 的过程。 组件将间接的接收props,而你必须确保一切正常。

我们先探讨如何在没有 React Context API 的情况下处理常见问题:

App.js

代码语言:javascript
复制
 1class App extends Component {
 2    state = {
 3        cars: {
 4            car001: { name: 'Honda', price: 100 },
 5            car002: { name: 'BMW', price: 150 },
 6            car003: { name: 'Mercedes', price: 200 }
 7        }
 8    };
 9    incrementCarPrice = this.incrementCarPrice.bind(this);
10    decrementCarPrice = this.decrementCarPrice.bind(this);
11
12    incrementCarPrice(selectedID) {
13        // a simple method that manipulates the state
14        const cars = Object.assign({}, this.state.cars);
15        cars[selectedID].price = cars[selectedID].price + 1;
16        this.setState({
17            cars
18        });
19    }
20
21    decrementCarPrice(selectedID) {
22        // a simple method that manipulates the state
23        const cars = Object.assign({}, this.state.cars);
24        cars[selectedID].price = cars[selectedID].price - 1;
25        this.setState({
26            cars
27        });
28    }
29
30    render() {
31        return (
32            <div className="App">
33                <header className="App-header">
34                    <img src={logo} className="App-logo" alt="logo" />
35                    <h1 className="App-title">Welcome to my web store</h1>
36                </header>
37                {/* Pass props twice */}
38                <ProductList
39                    cars={this.state.cars}
40                    incrementCarPrice={this.incrementCarPrice}
41                    decrementCarPrice={this.decrementCarPrice}
42                />
43            </div>
44        );
45    }
46}

ProductList .js

代码语言:javascript
复制
 1const ProductList = props => (
 2    <div className="product-list">
 3        <h2>Product list:</h2>
 4        {/* Pass props twice */}
 5        <Cars
 6            cars={props.cars}
 7            incrementCarPrice={props.incrementCarPrice}
 8            decrementCarPrice={props.decrementCarPrice}
 9        />
10        {/* Other potential product categories which we will skip for this demo: */}
11        {/* <Electronics /> */}
12        {/* <Clothes /> */}
13        {/* <Shoes /> */}
14    </div>
15);
16
17export default ProductList;
18

Cars.js

代码语言:javascript
复制
 1const Cars = props => (
 2    <Fragment>
 3        <h4>Cars:</h4>
 4        {/* Finally we can use data */}
 5        {Object.keys(props.cars).map(carID => (
 6            <Car
 7                key={carID}
 8                name={props.cars[carID].name}
 9                price={props.cars[carID].price}
10                incrementPrice={() => props.incrementCarPrice(carID)}
11                decrementPrice={() => props.decrementCarPrice(carID)}
12            />
13        ))}
14    </Fragment>
15);
16

Car.js

代码语言:javascript
复制
1const Cars = props => (
2    <Fragment>
3        <p>Name: {props.name}</p>
4        <p>Price: ${props.price}</p>
5        <button onClick={props.incrementPrice}>&uarr;</button>
6        <button onClick={props.decrementPrice}>&darr;</button>
7    </Fragment>
8);

当然,这不是处理数据的最好方式,但我希望能够用它说明为什么 prop drilling 很差劲。 那么 Context API 是如何帮我们避免这种情况呢?

介绍Context Web Store

让我们重构程序并演示它可以做些什么。 简而言之,Context API 允许你拥有一个存储数据的中央存储(是的,就像存储在 Redux 中一样)。你可以把任何组件直接插入到商店应用中,也可以切断 middleman!

两个状态流的示例:一个使用React Context API,另一个不用

重构非常简单 —— 我们不必对组件的结构进行任何修改。但是我们确实需要创建一些新组件:Provider 和 consumer。

1.初始化 Context

首先,我们需要创建context【https://reactjs.org/docs/context.html#reactcreatecontext】,后面可以使用它来创建 Provider 和 consumer。

MyContext.js

代码语言:javascript
复制
1import React from 'react';
2
3// this is the equivalent to the createStore method of Redux
4// https://redux.js.org/api/createstore
5
6const MyContext = React.createContext();
7
8export default MyContext;

2. 创建 Provider

完成后,我们可以导入 context 并用它来创建我们的 provider,我们称之为 MyProvider。在里面使用一些值初始化一个状态,你可以通过 value prop 共享我们的 provider 组件。 在例子中,我们将共享 this.state.cars 以及一些操纵状态的方法。 将这些方法可以看作是 Redux 中的 Reducer。

MyProvider.js

代码语言:javascript
复制
 1import MyContext from './MyContext';
 2
 3class MyProvider extends Component {
 4    state = {
 5        cars: {
 6            car001: { name: 'Honda', price: 100 },
 7            car002: { name: 'BMW', price: 150 },
 8            car003: { name: 'Mercedes', price: 200 }
 9        }
10    };
11
12    render() {
13        return (
14            <MyContext.Provider
15                value={{
16                    cars: this.state.cars,
17                    incrementPrice: selectedID => {
18                        const cars = Object.assign({}, this.state.cars);
19                        cars[selectedID].price = cars[selectedID].price + 1;
20                        this.setState({
21                            cars
22                        });
23                    },
24                    decrementPrice: selectedID => {
25                        const cars = Object.assign({}, this.state.cars);
26                        cars[selectedID].price = cars[selectedID].price - 1;
27                        this.setState({
28                            cars
29                        });
30                    }
31                }}
32            >
33                {this.props.children}
34            </MyContext.Provider>
35        );
36    }
37}
38

为了使 provider 可以访问其他组件,我们需要用它包装我们的应用程序(没错,就像 Redux 一样)。我们可以摆脱这些状态和方法,因为它们在 MyProvider.js 中定义。

App.js

代码语言:javascript
复制
 1class App extends Component {
 2    render() {
 3        return (
 4            <MyProvider>
 5                <div className="App">
 6                    <header className="App-header">
 7                        <img src={logo} className="App-logo" alt="logo" />
 8                        <h1 className="App-title">Welcome to my web store</h1>
 9                    </header>
10                    <ProductList />
11                </div>
12            </MyProvider>
13        );
14    }
15}
16

3. 创建 Consumer

我们需要再次导入 context 并用它包装我们的组件,它会在组件中注入context 参数。 之后,它非常直接。 你使用 **context **就像用 props 一样。 它包含我们在 MyProducer 中共享的所有值,我们所需要做的只是去使用它!

Cars.js

代码语言:javascript
复制
 1const Cars = () => (
 2    <MyContext.Consumer>
 3        {context => (
 4            <Fragment>
 5                <h4>Cars:</h4>
 6                {Object.keys(context.cars).map(carID => (
 7                    <Car
 8                        key={carID}
 9                        name={context.cars[carID].name}
10                        price={context.cars[carID].price}
11                        incrementPrice={() => context.incrementPrice(carID)}
12                        decrementPrice={() => context.decrementPrice(carID)}
13                    />
14                ))}
15            </Fragment>
16        )}
17    </MyContext.Consumer>
18);

我们似乎忘记了什么?是 ProductList !它使好处变得非常明显。 我们不必传递任何数据或方法。这个组件被简化,因为它只需要去渲染一些组件。

ProductList.js

代码语言:javascript
复制
 1const ProductList = () => (
 2    <div className="product-list">
 3        <h2>Product list:</h2>
 4        <Cars />
 5        {/* Other potential product categories which we will skip for this demo: */}
 6        {/* <Electronics /> */}
 7        {/* <Clothes /> */}
 8        {/* <Shoes /> */}
 9    </div>
10);

在本文中,我对 Redux 和 Context API 进行了一些比较。 Redux 最大的优势之一就是你的应用可以拥有一个可以从任何组件访问的中央存储。而使用新的 Context API,默认情况下你已经有了这个功能。 在巨大的宣传攻势下 Context API 将会使 Redux 变得过时。

对于那些只把 Redux 作为中央存储功能的人来说,可能确实如此。 如果你只使用 Redux 的这一个功能,现在可以使用 Context API 替换它,并避免在不使用第三方库的情况下进行 prop drilling。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 京程一灯 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍Context Web Store
  • 1.初始化 Context
  • 2. 创建 Provider
  • 3. 创建 Consumer
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档