const updateSearchTopStoriesState = (hits, page) => (prevState) => {
const { searchKey, results } = prevState
有人可以向我解释以上内容的作用吗?为什么有2个箭头功能?
这是整个代码
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 {
...
连续两个箭头功能被称为thunk。
简单来说,以这种格式可以更容易理解:
function updateSearchTopStoriesState = (hits, page) {
function updateState (prevState) {
...code
}
return updateState;
}
箭头功能意味着隐式返回。因此,如果看到两个箭头紧挨着,则意味着第一个函数返回一个函数。这不是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));