我正在制作一個顯示資料的表格
const [body, setBody] = useState<JSX.Element[]>()
const reduxSelectorValue = useSelector(state => state.someReducer.value) // [4,5,6,7]
const [thisState, setThisState] = useState<number[]>([1])
useEffect(()=>{
setThisState(reduxSelectorValue)
)
},[reduxSelectorValue])
useEffect(() => {
setBody(
thisState.map((value: number, index: number) => (
<div
onClick={() => {
setThisState((thisState) => {
const newThisState = thisState.slice()
newThisState[index] = newThisState[index] 1 - 3
return newThisState
})
}}
>
{value}
</div>
)),
)
}, [thisState])
render(
<ATableElement body={body}/>
)
當我點擊按鈕時沒有變化 body
我應該如何處理這個問題?
uj5u.com熱心網友回復:
以下是您解決問題的方法。
有一個存盤數字陣列的狀態。
map在狀態上創建按鈕。ATableElement如果您需要一個由另一個組件制成的容器,您可以將它們設為 的子項。當呼叫單擊偵聽器時呼叫該
handleClick函式。這會計算出容器內按鈕的索引,復制狀態,然后更新該新狀態的索引。然后,您可以使用更新后的陣列設定狀態。
const { useEffect, useState } = React;
function Example() {
const [ state, setState ] = useState([1, 2, 3, 4]);
useEffect(() => console.log(state), [state]);
function handleClick(e) {
// Destructure the children from the parent of
// the element that was clicked (ie
// all the input elements)
const { parentNode: { children } } = e.target;
// Find the index of the button that was clicked
const index = [...children].indexOf(e.target);
// Copy the state
const newState = [...state];
// Toggle the boolean at the index of
// the `newState` array
newState[index] = state[index] 1 - 3;
// Update the state
setState(newState);
}
return (
<ATableElement>
{state.map(n => {
return (
<button
onClick={handleClick}
>Click {n}
</button>
)
})}
</ATableElement>
);
};
function ATableElement({ children }) {
return <div>{children}</div>
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
uj5u.com熱心網友回復:
試試這個更正:
const reduxSelectorValue = useSelector(state => state.someReducer.value)
// [4,5,6,7]
const [thisState, setThisState] = useState<number[]>([1])
useEffect(()=>{
setThisState(reduxSelectorValue)
)
},[reduxSelectorValue])
body(list){
let bodyContent = list.map((value: number, index: number) => (
<div
onClick={() => {
setThisState((thisState) => {
const newThisState = thisState.slice()
newThisState[index] = newThisState[index] 1 - 3
return newThisState
})
}}
>
{value}
</div>
))
return <ATableElement body={bodyContent}/>
}
render(
return body(thisState)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/362753.html
標籤:javascript 反应 打字稿
上一篇:僅當有資料時才渲染表
