我有这个类组件,我想将其更改为功能组件
import { socket } from "../global/header";
class PlaceOrder extends Component {
constructor() {
super();
this.state = {
food_data: []
// this is where we are connecting to with sockets,
};
}
getData = foodItems => {
console.log(foodItems);
foodItems = foodItems.map(food => {
food.order = 0;
return food;
});
this.setState({ food_data: foodItems });
};
componentDidMount() {
socket.emit("initial_data");
var state_current = this;
socket.on("get_data", state_current.getData);
}
componentWillUnmount() {
socket.off("get_data", this.getData);
}}
我想将其更改为功能组件并使用react hook(useEffect),这是我的代码
const PlaceOrder = () => {
const [food_data,setFoodData] = useState([]);
const getData = foodItems => {
console.log(foodItems);
foodItems = foodItems.map(food => {
food.order = 0;
return food;
});
setFoodData(foodItems)
};
useEffect(() => {
socket.emit("initial_data");
socket.on("get_data", (data)=>{
// setFoodData(data)
getData(data)
console.log({data})
//setFoodData(data)
console.log({food_data})
// getData(data);
});
return () =>{
socket.off('get_data',(data)=>getData(data));
}
})
但这会导致无限循环,当我尝试添加一个空数组时,它不会更新状态。我是新来的人,可以告诉我我做错了什么