Created
January 29, 2024 08:44
-
-
Save PeterlitsZo/ababf3de23228622b5d01d400ff6d688 to your computer and use it in GitHub Desktop.
在列表中重渲染
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react' | |
import './App.css' | |
interface All { | |
h1: string; | |
txt: string; | |
has_button: boolean; | |
} | |
interface PureItemProps { | |
all: All; | |
buttonCallback: () => void; | |
waiting: boolean; | |
} | |
// 这个是一个纯函数。可以根据 Object 来进行渲染。 | |
function PureItem(props: PureItemProps) { | |
const button = ( | |
<button onClick={props.buttonCallback}>Click me!</button> | |
) | |
return ( | |
<div> | |
<h1>{props.all.h1}{props.waiting ? '(正在发送请求)' : ''}</h1> | |
<div>{props.all.txt}</div> | |
{props.all.has_button ? button : null} | |
</div> | |
) | |
} | |
interface ItemProps { | |
all: All; | |
} | |
// 这是一个不太纯的函数。 | |
function Item(props: ItemProps) { | |
const [all, setAll] = useState(props.all); | |
const [waiting, setWaiting] = useState(false); | |
const buttonCallback = async () => { | |
// 休息 1s。 | |
setWaiting(true); | |
await new Promise(r => setTimeout(r, 1000)); | |
setAll({ | |
h1: '新标题', | |
txt: '新文本', | |
has_button: false, | |
}); | |
setWaiting(false); | |
}; | |
return ( | |
<PureItem all={all} buttonCallback={buttonCallback} waiting={waiting} /> | |
) | |
} | |
function App() { | |
return ( | |
<> | |
{[...Array(10).keys()].map(_ => { | |
return ( | |
<Item all={{ h1: '标题', txt: '文本', has_button: true }} /> | |
); | |
})} | |
</> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment