旧代码现代化

将旧代码升级到现代写法

提示词

请将以下旧代码现代化:

源版本:[如ES5/React class component/jQuery]
目标版本:[如ES6+/React Hooks/Vue 3]

`
[粘贴旧代码]
`

现代化内容:
1. 使用新语法特性
2. 迁移到新API
3. 移除废弃用法
4. 使用现代最佳实践
5. 保持功能完全一致

输出:
1. 现代化后的代码
2. 主要改动清单
3. 需要注意的breaking changes

示例输出

React Class → Hooks 迁移:

// 旧代码(Class组件)
class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { user: null, loading: true };
    this.handleUpdate = this.handleUpdate.bind(this);
  }
  
  componentDidMount() {
    fetchUser(this.props.userId).then(user => 
      this.setState({ user, loading: false })
    );
  }
  
  handleUpdate(data) {
    updateUser(data).then(() => this.setState({ user: data }));
  }
  
  render() {
    if (this.state.loading) return <Spinner />;
    return <div>{this.state.user.name}</div>;
  }
}
// 新代码(Hooks)
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchUser(userId).then(data => {
      setUser(data);
      setLoading(false);
    });
  }, [userId]);

  const handleUpdate = async (data) => {
    await updateUser(data);
    setUser(data);
  };

  if (loading) return <Spinner />;
  return <div>{user.name}</div>;
}
0

评论 0

更多

登录后可点赞、收藏、评论和举报。

还没有评论,先发起一个具体问题。