【发布时间】:2017-12-25 19:48:12
【问题描述】:
react 是否可以在调用 re-render() 函数之前准备一个要在 JSX 中显示的变量?
例如:
count_function() {
e.g.
return number_of_children_having_state_#
}
a_prerender_function() { // Which one componentWillUpdate ?? But in that case, how to pass it to the render function
// const count = this.count_function() // This can't be put in state, otherwise 'infinite-loop'
}
render () {
// const count = this.count_function() // This is only called at the first render! But not on next re-render
return (
<div>
{count}
</div>
)
}
我无法在 render() 函数中更新这个变量,因为我需要在每次重新渲染时刷新它,并且渲染函数只被调用一次。 我不能为此使用状态变量,否则我会得到一个无限循环的重新渲染。
【问题讨论】:
-
错误,每次组件需要重新渲染时都会调用渲染函数。通读反应文档facebook.github.io/react/docs/state-and-lifecycle.html
-
你能发布一个更完整的代码版本吗?由于每次渲染时都应该调用 render ,如果每次都没有调用 render ,那么可能是其他问题,例如,您的 count_function。
-
目前还不清楚你想要实现什么。但是您确实需要了解反应组件的生命周期 (facebook.github.io/react/docs/react-component.html)。如果要根据 count_function() 结果设置组件状态,则需要小心选择执行此操作的位置。永远不要在 render() 或 componentWillUpdate() 或从它们调用的函数中设置状态。如果您需要在组件挂载(首次渲染)之前为其设置初始状态,请在组件的 constructor() 中执行此操作。
-
你的 count 变量计数是多少?
-
它正在计算将两个特定状态变量设置为例如的嵌套子项的数量。 '真实'。