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