高阶组件

2018-02-27  本文已影响0人  iambabewin
0.作为值的函数与部分调用

就像是数字,字符串,布尔值一样,函数也是值,
意味着可以像传递其他数据一样传递函数,可以将函数作为参数传递给另外一个函数

const execute = (someFunction) => someFunction()
execute(()=> alert('Excuted'))

也可以在函数中返回一个函数:
从函数返回函数可以帮助我们追踪初始输入函数。
下面的函数接受一个数字作为参数,并返回一个将该参数乘以新参数的函数:

const multiply =(x) => (y) => x*y
multiply                  // (x) => (y) => x * y
multiply(5)               // (y) => x * y

const multiplyByFive = multiply(5)
const multiplyBy100 = multiply(100)
multiplyByFive(20)  //100
multiply(5)(20)     // 100
multiplyBy100(5)    //100
multiplt(100)(5)    //500

在只传入一个参数调用 multiply 函数时,即部分调用该函数。通过部分调用可以创建一个预定义功能的新函数。multiplyByFive() ,multiplyBy100()

好处:通过部分调用这种方式可以编写可读性更高,更易于理解的代码。

1.高阶函数

定义:接受函数作为参数的函数。
eg: map 函数,一个数组遍历的方法

const square = (x) => x * x
[1,2,3].map(square)
const map = (fn, array)=> {
const mappedArray = []
for(let i = 0; i< array.length; i++) {
  mappedArray.push(
    // apply fn with the current element of the array
    fn(array[i])
  )
}
return mappedArray
}
//使用以上的 map 版本来对数组作平方:
const square = (x) => x * x
console.log(map(square,[1,2,3,4,5]))  //[1,3,9,16,25]

返回一个<li>的React元素数组:

const HeroList = ({ heroes }) => (
  <ul>
      {map((hero)=>(
        <li key ={hero}>{hero}</li>
      ),heroes)}
  </ul>
)

<HeroList heros=[
    "Wonder Woman",
    "Black Widow",
    "Spider Man",
    "Storm",
    "Deadpool"
]/>

/*
<ul>
    <li>Wonder Woman</li>
    <li>Black Widow</li>
    <li>Spider Man</li>
    <li>Storm</li>
    <li>Deadpool</li>
</ul>
*/
2.高阶组件(Higher-Order Components(HOCs) for React Nexbies)

在React中,任何返回JSX的函数都被称为无状态组件,简称为函数组件。
高阶组件则是接受组件作为参数并返回组件的函数。
将HTTP请求的结果传递给函数组件:

withGists 会传递gists api 调用的结果,并且可以在任何组件上使用。

const withGists = (PassedComponent) =>
class WithGists extends React.Component {
    state = {
        gists: []
    }
    componentDidMount(){
        fetch("https://api.github.com/gists/public")
        .then((r) => r.json())
        .then((gists) => this.setState({
            gists: gists
        }))
    }
    render(){
        return(
            <PassedComponent
                {...this.props}
                gists={this.state.gists}
            />
        )
    }
}

const Gists = ({ gists }) => {
    <pre>{JSON.stringify(gists, null, 2)}</pre>
}

const GistsList = withGists(Gists)

<GistsList />

// => Before api request finished:
// <Gists gists={[]} />
// 
// => Afterapi request finished:
// <Gists gists={[
//   {/*···*/},
//   {/*···*/},
//   {/*···*/},
// ]} />
上一篇下一篇

猜你喜欢

热点阅读