Javascript 使用onAction={}属性动态创建的JSX元素,不更新状态(它们已断开)
考虑这两个Javascript 使用onAction={}属性动态创建的JSX元素,不更新状态(它们已断开),javascript,reactjs,jsx,es6-promise,Javascript,Reactjs,Jsx,Es6 Promise,考虑这两个setState变量,它们的值在承诺成功后发生变化(例如ajax调用) 使用指定时调用的useffecthook(在第一次渲染的示例中)做出承诺 NORMAL按钮将console.log()ajax\u响应 但是{showAjax}控制台中动态创建的按钮只记录ajax\u响应的初始状态 所以输出如下所示 在{showAjax} 普通按钮 TL:DR 使用ONCLICK属性动态生成的REACT元素被破坏:它们不显示更新的状态映射似乎起到了作用,只需在.map函数中使用值更改{i}
setState
变量,它们的值在承诺成功后发生变化(例如ajax调用)
使用指定时调用的useffect
hook(在第一次渲染的示例中)做出承诺
NORMAL按钮将console.log()
ajax\u响应
但是{showAjax}
控制台中动态创建的按钮只记录ajax\u响应的初始状态
- 所以输出如下所示
- 在
{showAjax}
- 普通按钮
TL:DR
使用ONCLICK属性动态生成的REACT元素被破坏:它们不显示更新的状态映射似乎起到了作用,只需在.map函数中使用值更改{i}
const [ajax_response,getAjax_response] = useState("awaiting response"); //This one stores the ajax call response
const [showAjax,setShowAjax] = useState([]) //This one displays it
useEffect(() => {
fetchData().then(data => {
//Here it stores the value in the first useState variable
getAjax_response(data[0])
//Here it loops throw the data and DYNAMICALLY CREATES some attributes based on the repsponse
//In this example it just fetches a single number from the ajax call
//And performs a loop until it reaches that (IRELEVANT)
for (let i=0;i < data[0];i++) {
let styled_data = <p onClick={() => console.log(ajax_response)}>{i}</p>;
setShowAjax(prev => [...prev,styled_data])
}
})
},[])
return (
<div className="App">
<button onClick={() => console.log(ajax_response)}>THE NORMAL BUTTON</button> //Button set manually
{showAjax} //The JSX elements set dynamically
</div>
);
>>> awaiting response
>>> CAT
let styled_data = <p onClick={() => console.log(ajax_response)}>{i}</p>;
setShowAjax(prev => [...prev,styled_data])
for (let i=0;i < data[0];i++) {
// Modify this to store whatever data you need.
// Your example only used numbers, so i replicated that, but i expect your real code needs more.
setShowAjax(prev => [...prev, i]);
}
//...
return (
<div className="App">
<button onClick={() => console.log(ajax_response)}>THE NORMAL BUTTON</button>
{showAjax.map(value => (
<p onClick={() => console.log(ajax_response)}>{value}</p>
)}
</div>
);