admin管理员组文章数量:1279089
I am making a WordPress Guttenberg Block to fetch a post and display it's title.
But it is giving me the error 301 which is: Too many re-renders. React limits the number of renders to prevent an infinite loop. .html/?invariant=301
I tried translating this articles class based component to a functional one /
I have tested the component and I think the error is in the if statements below, it could be the setResult()
re-rendering the component. But suposably it only rerenders if the result is something new, right? maybe the functionality is different on WordPress than on pure React.
Here is the code:
// custom hook for constructor like functionality
const useConstructor = callback => {
const [ hasBeenCalled, setHasBeenCalled ] = useState(false)
if (hasBeenCalled) return
callback()
setHasBeenCalled(true)
}
const getPost = ({properties}) => {
const [ options, setOptions ] = useState([])
const [ result, setResult ] = useState(`Loading...`)
const [ id, setId ] = useState(properties.attributes.id)
const [ posts, setPosts ] = useState(null)
const updateId = newId => {
newId = Number(newId)
setId(newId)
properties.setAttributes({ id: newId })
}
const createOptions = source => {
source.forEach( post => {
setOptions( oldOptions => {
return [
...oldOptions,
{
label: post.title.rendered,
value: post.id
}
]
})
})
}
useConstructor(() => {
console.log(`Entering constructor`)
fetch(`../../wp-json/wp/v2/posts`)
.then(response => response.json())
.then(posts => {
setPosts(posts)
createOptions(posts)
})
})
if (posts !== null) {
const postIsSelected = id !== -1
if (postIsSelected) {
const post = posts.find(post => post.id === id)
setResult(post.title.rendered)
} else setResult(`Select a post.`)
} else setResult(`No posts... Create some first.`)
return [
<InspectorControls>
<SelectControl
label = 'Select a Post'
value = {id}
options = {options}
onChange = {updateId}
/>
</InspectorControls>,
result
]
}
本文标签: postsWordPress React rerendering to many times
版权声明:本文标题:posts - WordPress React re-rendering to many times 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741239064a2363605.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论