简体   繁体   English

当父母更新它时,孩子的道具不会更新它是 state

[英]Props in child doesn't update when parent updates it's state

I've spent a few days on this and it is driving me crazy now.我在这上面花了几天时间,现在快把我逼疯了。

I have a state in a parent component containing an Array[string] of selected squares which is passed to the child component (a map) along with the set function from the hook.我在父组件中有一个 state,其中包含一个选定方块的 Array[string],它与钩子中的集合 function 一起传递给子组件(地图)。 The issue is that when I set the new squares they are changed in the parent, but on selection of another square it is not taking into account the already selected squares.问题是,当我设置新方块时,它们在父级中发生了变化,但在选择另一个方块时,它没有考虑到已经选择的方块。

function Parent(props){
    const [selectedSquares, setSquares] = useState([]);
    
    useEffect(() => {
        console.log('parent useEffect', selectedSquares);
    }, [selectedSquares]);
    
    return (
        <Child selectedSquares={selectedSquares}
               handleSquaresChange={setSquares}
        />
    )
}

function Child(props){
   const {selectedSquares, handleSquaresChange} = props;

    useEffect(() => {
        console.log('child useEffect', selectedSquares)
    }, [selectedSquares]);

    const handleSelect =  evt => {
        if(evt.target){
           const features = evt.target.getFeatures().getArray();
           let selectedFeature = features.length ? features[0] : null;
           if (selectedFeature) {
               console.log('select (preadd):', selectedSquares);
               const newTile = selectedFeature.get('TILE_NAME');
               const newSquares = [...selectedSquares];
               newSquares.push(newTile);
               const newTest = 'newTest';
               handleSquaresChange(newSquares);
               console.log('select (postadd):', newSquares);
        }
    }
    
    return(
        <Map>
            <Select onSelect={handleSelect}/>
        </Map>
    )
}

On the first interactionSelect component I get this output from the console:在第一个 interactionSelect 组件上,我从控制台得到这个 output:

parent useEffect: [] , parent useEffect: [] ,

child useEffect: [] , child useEffect: [] ,

select (preadd):[] , select (preadd):[] ,

child useEffect:['NX'] , child useEffect:['NX'] ,

parent useEffect: ['NX'] , parent useEffect: ['NX'] ,

select (postadd): ['NX'] . select (postadd): ['NX']

Making the second selection this is added to the console:进行第二个选择,将其添加到控制台:

select (preadd):[] , select (preadd):[] ,

select (postadd): ['SZ'] , select (postadd): ['SZ']

child useEffect:['SZ'] , child useEffect:['SZ'] ,

parent useEffect: ['SZ'] . parent useEffect: ['SZ']

Turns out there is an addEventListener in the library I am using that is going wrong.原来我正在使用的库中有一个 addEventListener 出错了。 Thanks to everyone who responded but turns out the issue was not with React or the state stuff.感谢所有做出回应的人,但事实证明问题不在于 React 或 state 之类的东西。

Consider something like the code below.考虑类似下面的代码。 Your parent has an array with all your options.你的父母有一个包含你所有选项的数组。 For each option, you render a child component.对于每个选项,您都渲染一个子组件。 The child component handles the activity of its own state.子组件处理它自己的 state 的活动。

function Parent(props){
    // array of options (currently an array of strings, but this can be your squares)
    const allOptions = ['opt 1', 'opt 2', 'opt 3', 'etc']; 
     
    return (
        <>
            // map over the options and pass option to child component
            {allOptions.map((option) => <Child option={option}/>)} 
        </>
    )
}

function Child({ option }){
    const [selected, setSelected] = useState(false); // default state is false
     
    return (
        <>
            // render option value
            <p>{option}</p> 
            // shows the state as selected or not selected
            <p>Option is: {selected ? "selected" : "not selected"}</p> 
            // this button toggles the active state
            <button onClick={() => setSelected(!selected)}>Toggle</button>
        </>
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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