Skip to content

Commit

Permalink
feat: use callback
Browse files Browse the repository at this point in the history
  • Loading branch information
afeiship committed May 27, 2021
1 parent 25273fd commit 0b984ae
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sites/src/App.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Example, ExampleUseMemo } from './modules/memo-callback';
import { ExmapleNoCallback, ExampleUseCallback } from './modules/callback-use';
import ReactMemoDemo from './modules/react-memo-demo';
import CallbackUse2 from './modules/callback-use2';

export default (props) => {
return (
Expand All @@ -10,6 +11,7 @@ export default (props) => {
<ExmapleNoCallback />
<ExampleUseCallback />
<ReactMemoDemo />
<CallbackUse2 />
</div>
);
};
36 changes: 36 additions & 0 deletions sites/src/modules/callback-use2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React, { useEffect, useCallback, useState } from 'react';
import styled from 'styled-components';

const C1 = styled.div`
width: 80%;
margin: 20px auto;
border: 1px solid #ccc;
`;
// 用于记录 getData 调用次数
let count = 0;

function App() {
const [val, setVal] = useState('');

function getData() {
setTimeout(() => {
setVal('new data comming' + count);
console.log('newData');
count++;
}, 500);
}

const optGetData = useCallback(getData, []);

return <Child val={val} getData={optGetData} />;
}

function Child({ val, getData }) {
useEffect(() => {
getData();
}, [getData]);

return <C1>{val}</C1>;
}

export default App;

0 comments on commit 0b984ae

Please sign in to comment.