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

 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);1112    incrementCarPrice(selectedID) {13        // a simple method that manipulates the state14        const cars = Object.assign({}, this.state.cars);15        cars[selectedID].price = cars[selectedID].price + 1;16        this.setState({17            cars18        });19    }2021    decrementCarPrice(selectedID) {22        // a simple method that manipulates the state23        const cars = Object.assign({}, this.state.cars);24        cars[selectedID].price = cars[selectedID].price - 1;25        this.setState({26            cars27        });28    }2930    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                <ProductList39                    cars={this.state.cars}40                    incrementCarPrice={this.incrementCarPrice}41                    decrementCarPrice={this.decrementCarPrice}42                />43            </div>44        );45    }46}

ProductList .js

 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);1617export default ProductList;18

Cars.js

 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

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

1import React from 'react';23// this is the equivalent to the createStore method of Redux4// https://redux.js.org/api/createstore56const MyContext = React.createContext();78export default MyContext;

2. 创建 Provider

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

MyProvider.js

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    };1112    render() {13        return (14            <MyContext.Provider15                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                            cars22                        });23                    },24                    decrementPrice: selectedID => {25                        const cars = Object.assign({}, this.state.cars);26                        cars[selectedID].price = cars[selectedID].price - 1;27                        this.setState({28                            cars29                        });30                    }31                }}32            >33                {this.props.children}34            </MyContext.Provider>35        );36    }37}38

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

App.js

 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

 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

 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。

©著作权归作者所有:来自51CTO博客作者mb5ff980b461ced的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. 怎样开发可重用组件并发布到NPM [每日前端夜话0x24]
  2. Python22个构造函数法-助力数据挖掘与分析
  3. 干货!python与MySQL数据库的交互实战
  4. 用python数据分析了北京积分落户名单,发现……
  5. 数据透视表,一篇就够了
  6. Excel数据获取
  7. 一文带你了解数据保护的重要性
  8. 数据分析方法论
  9. 数据处理

随机推荐

  1. 详解Golang数组的传递
  2. 分享golang实现文件传输小demo
  3. go语言中run与build命令的区别是什么?
  4. 解决GO语言安装air框架时遇到go: inconsi
  5. 分享5种文件变更时自动重载Go程序的方法
  6. go语言中普通函数与方法的区别是什么?
  7. golang中方法的receiver为指针和不为指针
  8. 分享一次腾讯Go开发岗位面试经过
  9. go是什么语言
  10. 详解Golang如何对excel进行处理