Compare commits

..

2 Commits

Author SHA1 Message Date
laktionov-as 12515f925d Сделали таймер 2026-05-28 20:45:57 +03:00
laktionov-as b3662b759f class components 2026-05-28 20:29:26 +03:00
4 changed files with 93 additions and 108 deletions
-27
View File
@@ -8,7 +8,6 @@
"name": "store-client", "name": "store-client",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.100.14",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0" "react-dom": "^19.1.0"
}, },
@@ -1305,32 +1304,6 @@
"win32" "win32"
] ]
}, },
"node_modules/@tanstack/query-core": {
"version": "5.100.14",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.100.14.tgz",
"integrity": "sha512-5X41dGpxgeaHISCRW2oYwcSycZeULZzAunaudXT9ov1KOTj9xwt0CH6hbwqP1/z74ZWF7rYFnDpyYH07XFcZew==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.100.14",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.100.14.tgz",
"integrity": "sha512-oOr6aRdSFEwWhzxEkD/9ZcItM3+LjBSkeVmadWKwUssAHTsqd/7bOjWrX4AbvEkoEhgAxzN0Xk6H/aYzXiYBAw==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.100.14"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
-1
View File
@@ -10,7 +10,6 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.100.14",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0" "react-dom": "^19.1.0"
}, },
+86 -71
View File
@@ -1,93 +1,108 @@
import React, {useState, useEffect, useRef } from 'react' import React from 'react'
//import { useQuery } from '@tanstack/react-query'
function useWindowWidth() { class MyComponent extends React.Component {
const [width,setWidth] = useState(window.innerWidth) constructor(props) {
super(props);
useEffect(() => { this.state = { data: null };
const handleResize = () => setWidth(window.innerWidth); this.handleClick = this.handleClick.bind(this);
window.addEventListener('resize',handleResize);
return () => window.removeEventListener('resize',handleResize);
},[])
return width
} }
function useLocalStorage(key, initValue) { render() {
const [value, setValue] = useState(()=>{ return (
const stored = localStorage.getItem(key); <div>
return stored !== null ? JSON.parse(stored) : initValue {this.state.data ? (
}) <div>Данные: {this.state.data}</div>
) : (
useEffect(() => { <div>Загрузка...</div>
localStorage.setItem(key, JSON.stringify(value)) )}
},[key, value]) <button onClick={this.handleClick}>Обновить</button>
</div>
return [value,setValue]
}
/*
function useUserData(userId) {
return useQuery(
['user',userId],
() => fetch(`/api/user/${userId}`).then(res => res.json()),
{refetchOnWindowFocus: false}
) )
}*/ }
function useInput(initValue, validate) { componentDidMount() {
const [value, setValue] = useState(initValue); fetch('https://api.example.com/data')
const [error, setError] = useState(null); .then(responce => responce.json())
.then(json => this.setState({data: json}));
const onChange = e => { this.timerId = setInterval(()=> console.log('Tick'), 1000);
const newValue = e.target.value }
setValue(newValue)
if (validate) { componentWillUnmout() {
const validationResult = validate(newValue) clearInterval(this.timerId);
setError(validationResult) }
handleClick() {
this.setState({data: 'Данные'})
} }
} }
return { value, error, onChange } class MyComponent2 extends React.Component {
controller = new AbortController()
componentDidMount() {
fetch('https://api.example.com/data',{ singnal: this.controller.signal })
.then(responce => responce.json())
.then(json => this.setState({data: json}))
.catch(error => {
if(error.name == 'AbortError') {
console.log('Aborted');
} else {
console.log('Other error',error);
}
});
} }
function useInterval(callback, delay) { componentWillUnmount() {
const savedCallback = useRef() this.controller.abort()
}
}
class MyComponent3 extends React.Component {
componentDidMount() {
this.loadData();
}
useEffect(()=>{ async loadData() {
savedCallback.current = callback try {
},[callback]); const response = await fetch('https://api.example.com/data');
const data = await response.json();
this.setSate({ data });
} catch {
console.log('error');
}
}
}
useEffect(()=>{ class Timer extends React.Component {
if (delay == null) return constructor(props) {
const id = setInterval(()=>{ super(props);
savedCallback.current() this.state = { seconds: 0 }
},delay); }
return () => clearInterval(id);
},[delay]) componentDidMount() {
console.log('Timer mounted');
this.interval = setInterval(()=>{
this.setState(prevState => ({seconds: prevState.seconds + 1}))
},1000);
}
componentWillUnmount() {
console.log('Timer unmount');
clearInterval(this.interval);
}
render() {
return <h2>Прошло секунд: {this.state.seconds}</h2>
}
} }
function App() { function App() {
const width = useWindowWidth(); const [show,setShow] = React.useState(true);
const [theme, setTheme] = useLocalStorage('theme','light');
const username = useInput(
'',
value => value.length < 3 ? 'минимум 3 символа' : null
)
return ( return (
<> <>
<h1>Hello, React!{width}</h1> <h1>Таймер с классом</h1>
<button onClick={()=>{ <button onClick={()=>setShow(prev => !prev)}>{show ? 'Скрыть' : 'Показать'} таймер</button>
setTheme(theme === 'light' ? 'dark' : 'light') {show && <Timer />}
}}>
Сменить тему
</button>
<p><input type="text"
value={username.value}
onChange={username.onChange} />
{ username.error ? username.error : '' }
</p>
</> </>
) )
} }
-2
View File
@@ -4,7 +4,5 @@ import { createRoot } from 'react-dom/client'
import App from './App.jsx' import App from './App.jsx'
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode>
<App /> <App />
</StrictMode>
) )