【问题标题】:Lifting function in reactjs [duplicate]reactjs中的提升功能[重复]
【发布时间】:2020-03-12 19:37:11
【问题描述】:
const updateSearchTopStoriesState = (hits, page) => (prevState) => {
const { searchKey, results } = prevState

任何人都可以向我解释上述内容是做什么的吗?为什么有两个箭头函数?

这是完整的代码

const updateSearchTopStoriesState = (hits, page) => (prevState) => {
const { searchKey, results } = prevState;
const oldHits = results && results[searchKey]
? results[searchKey].hits
: [];
const updatedHits = [
...oldHits,
...hits
];
return {
results: {
...results,
[searchKey]: { hits: updatedHits, page }
},
isLoading: false
};
};
class App extends Component {
...

【问题讨论】:

    标签: javascript reactjs lifting


    【解决方案1】:

    连续的两个箭头函数称为 thunk。

    只是用这种格式更容易理解:

    function updateSearchTopStoriesState = (hits, page) {
       function updateState (prevState) {
        ...code
       }
       return updateState;
    }
    

    【讨论】:

    • 为什么不只是函数 updateState (prevState) { ...code with hits, page}
    【解决方案2】:

    箭头函数中的箭头表示隐式返回。因此,如果您看到两个箭头相互跟随,则表示第一个函数返回一个函数。这不是 React 的东西,而是 ES2016 的东西。如果是这样,上面的答案将是正确的:

    function updateSearchTopStoriesState = (hits, page) {
       return function updateState(prevState) {
        ...code
       }
    //Anything you put here would be disregarded since it is after the return statement.
    }
    

    将此视为一个基本示例:

    const add = num1 => num2 => num3 => num1+num2+num3;
    
    console.log(add(3)(4)(5));
    

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 2011-01-11
      • 2021-09-15
      • 2020-11-25
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多