So Posts
is a React 函数组件 https://reactjs.org/docs/components-and-props.html#function-and-class-components.
所有 Function 组件都会接收一个 props 对象作为其第一个参数。
const Posts = (props) => { /* ... */ }
props 将始终是一个包含渲染组件时传递给它的 props 的对象,例如:
import Posts from './path/to/Posts'
function SomeParentComponent() {
return <Posts limit={10} categories={{news:true, sports:false}} />
}
在这种情况下props
将是一个如下所示的对象:
{
limit : 10,
categories : {
news : true,
sports : false,
}
}
您当然可以解构组件中的 props 对象:
const Posts = (props) => {
const {
limit,
categories
} = props
// ... other stuff
}
但是您可以更进一步,执行所谓的“拆包”以解构嵌套属性
const Posts = (props) => {
const {
limit,
categories : {
sports,
news
}
} = props
// ... other stuff
}
最后,您可以在参数相同的情况下内联解构和解包对象,而不是在函数体中执行此操作。
const Posts = ({limit, categories:{news,sports}}) => {
// ... other stuff
}
这就是您的代码示例正在执行的操作。
看起来它期望父组件传入一个函数作为getPosts
prop,在调用时将首先设置posts.loading
为 true,加载帖子,然后设置posts.loading
为假。前任:
function SomeParentComponent() {
const [loading, setLoading] = useState(false)
const [posts, setPosts] = useState([])
const loadPosts = useCallback(async () => {
setLoading(true)
const loadedPosts = await loadPostsSomehow()
setPosts([posts, ...loadedPosts])
setLoading(false)
}, [])
return <Posts getPosts={loadPosts} post={{posts, loading}} />
}
确保使用useCallback
在这里获取记忆回调,否则你将陷入无限循环
**EDIT**
实际查看提供的链接后,实际上略有不同。而不是post
父组件提供的对象,实际上是redux提供的,但逻辑本质上是一样的。不同之处在于,不是父组件更改加载和发布状态,而是通过 redux 状态管理完成。