[英]How do I prevent ReactJS onclick function from running on render
[英]How do I render data from a callback function in reactjs?
我向我的 Django 后端发出请求,数据是一个信息列表。 我需要做的是为列表中的每个项目渲染一段 HTML,这个列表是异步检索的。 但是,在我返回一些 HTML 的render()
,我无法将其放在异步函数中。 我从来没有必要在反应中使用它:
var allLeads = []
// get a list of all the leads from the Django backend
const getAllLeads = (callback) => {
const leads = fetch("http://127.0.0.1:8000/api/v1/leads/", {method:'get', headers: {"Content-Type": "application/json"}})
.then(function(result){
//console.log("result", await result.text())
return result.text()
})
.then(async function(result){
// console.log("R2", result)
allLeads = result.slice()
// console.log("ALL", allLeads)
callback(allLeads)
return await leads
})
我的组件类:
class Home extends React.Component {
state = {
dataType: "", // store the type of data for the type of operation that should be sent to the backend. For example "create" will have the data for creating data
data: {},
displayOptions: false
}
leads = []
async handleChange(event){
event.preventDefault()
this.state.displayOptions = true
}
render() {
getAllLeads(function(data){
console.log("DATA", data)
return data
})
return (
<div className="App">
test
</div>
)
}
}
export default Home;
在getAllLeads
我成功地记录了数据,但我不知道如何在返回函数中使用该数据。 或者我什至如何使用异步数据将状态设置为列表,例如,以便我可以显示状态内的信息?
所以这里有几个问题,首先, this.setState({})
状态赋值,你必须使用this.setState({})
。 因为在引擎盖下它会触发 React Fiber 的重新计算。 我给出的另一个建议是在componentDidMount()
生命周期钩子上触发 API 调用,你可以让他异步,然后等待结果并调用this.setState({ data })
。
class Home extends React.Component {
state = {
dataType: "",
data: {},
leads: [],
displayOptions: false
}
async componentDidMount() {
const leads = await getAllLeads((data) => return data);
this.setState({ leads });
}
render() {
return (
<div className="App">
test
</div>
)
}
}
export default Home;
我还建议重构您的函数以获取线索,因为从 a 内部返回然后不返回任何内容。 使用async
和await
代替。 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.