简体   繁体   中英

Create a counter for .map that persists across component mount/unmount

I have a React component that is being mounted/unmounted several times. Within the component, I need multiple.maps, that need to be numbered.

I cannot seem to get a counter that will persist across mount/unmount, so that the.map values will increment appropriately. I've been trying with React Hooks, but keep running to the issue of "too many re-renders"

My component is:

    const url = `http://mysite.test/jsonapi/paragraph/lo_ec_ac/${props.id}`
    const [data,loading] = useFetch(url);
    const Ac = data.data;
    const [state,setState] = useState({counter:0});

    return(
        <Fragment>
        {loading ? ("Loading...") : (
            <Fragment>
                <tr>
                    <td colSpan="2">LO{props.LoNum} {Ac.attributes.field_lo}</td>
                </tr>
                <tr>
                    <td>
                        {Ac.attributes.field_pass.map((pass,index)=>
                            <div>{setState({counter:state.counter+1})}{state.counter}{Ac.attributes.field_pass}</div>
                        )}
                    </td>
                    <td>
                        {Ac.attributes.field_merit}
                    </td>
                    <td>
                        {Ac.attributes.field_dist}
                    </td>
                </tr>
            </Fragment>
        )}
        </Fragment>
    )
}

export default UnitAc

I'd be extremely grateful for any pointers on how to make this work.

Since you already have the index of each item from map , you don't need any counter state, and by removing it it'll fix your state management errors as well.

    const url = `http://mysite.test/jsonapi/paragraph/lo_ec_ac/${props.id}`
    const [data,loading] = useFetch(url);
    const Ac = data.data;

    return(
        <Fragment>
        {loading ? ("Loading...") : (
            <Fragment>
                <tr>
                    <td colSpan="2">LO{props.LoNum} {Ac.attributes.field_lo}</td>
                </tr>
                <tr>
                    <td>
                        {Ac.attributes.field_pass.map((pass,index)=>
                            <div>{index + 1}{Ac.attributes.field_pass}</div>
                        )}
                    </td>
                    <td>
                        {Ac.attributes.field_merit}
                    </td>
                    <td>
                        {Ac.attributes.field_dist}
                    </td>
                </tr>
            </Fragment>
        )}
        </Fragment>
    )
}

export default UnitAc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM