我有一个有状态的功能组件,在这里我也使用sortablejs。
const myComponent = () => {
const [myData, setMyData] = useState([...some initial array data...]);
const testMe = () => console.log(myData)
useEffect(() => {
const sortableContainer = document.querySelector(".slick-track");
Sortable.create(sortableContainer, {
onEnd: () => testMe() //onEnd is a callback from sortablejs api, that fires after we drag an item
}, []);
因此,无论myData在组件生命周期中如何变化,在此回调内部它始终显示初始数据。那么是否有可能在此回调中获取当前的myData
值?
答案 0 :(得分:0)
在这里https://stackoverflow.com/a/54528980/2810565
找到了答案我只应该这样使用prevState:
const testMe = () => {
setMyData(currentData => {
console.log('Here is my current data', currentData);
return ([...prevState, //here add changes to state]);
})
}