最佳答案
我在玩 反应钩,面临着一个问题。 当我试图使用事件侦听器处理的按钮来控制它时,它显示了错误的状态。
CodeSandbox: < a href = “ https://CodeSandbox.io/s/lrxw1wr97m”rel = “ norefrer”> https://CodeSandbox.io/s/lrxw1wr97m
为什么它显示了错误的状态?
在第一张卡中,Button2
应该在控制台中显示 2
卡。有什么想法吗?
const { useState, useContext, useRef, useEffect } = React;
const CardsContext = React.createContext();
const CardsProvider = props => {
const [cards, setCards] = useState([]);
const addCard = () => {
const id = cards.length;
setCards([...cards, { id: id, json: {} }]);
};
const handleCardClick = id => console.log(cards);
const handleButtonClick = id => console.log(cards);
return (
<CardsContext.Provider
value={{ cards, addCard, handleCardClick, handleButtonClick }}
>
{props.children}
</CardsContext.Provider>
);
};
function App() {
const { cards, addCard, handleCardClick, handleButtonClick } = useContext(
CardsContext
);
return (
<div className="App">
<button onClick={addCard}>Add card</button>
{cards.map((card, index) => (
<Card
key={card.id}
id={card.id}
handleCardClick={() => handleCardClick(card.id)}
handleButtonClick={() => handleButtonClick(card.id)}
/>
))}
</div>
);
}
function Card(props) {
const ref = useRef();
useEffect(() => {
ref.current.addEventListener("click", props.handleCardClick);
return () => {
ref.current.removeEventListener("click", props.handleCardClick);
};
}, []);
return (
<div className="card">
Card {props.id}
<div>
<button onClick={props.handleButtonClick}>Button1</button>
<button ref={node => (ref.current = node)}>Button2</button>
</div>
</div>
);
}
ReactDOM.render(
<CardsProvider>
<App />
</CardsProvider>,
document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id='root'></div>
我使用的是 React 16.7.0-alpha.0和 Chrome 70.0.3538.110
顺便说一下,如果我用一个 class 重写 CardsProvider,问题就解决了。 使用类: < a href = “ https://CodeSandbox.io/s/w2nn3mq9vl”rel = “ norefrer”> https://CodeSandbox.io/s/w2nn3mq9vl