【发布时间】:2018-11-23 06:23:42
【问题描述】:
我有一个应用程序组件,它采用一个嵌套组件。嵌套组件返回由其局部状态变量之一的长度确定的按钮数量。每个按钮都运行一个程序化的 this.setState() 函数以在单击时显示一组新数据。这是描述的代码,下面是我的问题:
class App extends React.Component {
render() {
return (
<div className='container'>
<Buttons />
</div>
)
}
}
class Buttons extends React.Component {
state = {
variableState,
count: 0,
chosen: 0,
}
upOne = x => {
this.setState(prevState => ({
count: prevState.count + 1,
chosen: x,
}))
console.log('running')
}
componentDidUpdate() {
console.log('componentupdated')
}
render() {
const {variableState, count, chosen} = this.state
const {upOne} = this
return (
<div>
{
variableState[count].answers.map((s, t) => <button onClick={() => upOne(t + 1)}>{s}</button>)
}
</div>
)
}
}
const variableState = [
{
answers: [
'one',
'two',
'three',
'four',
]
}
]
ReactDOM.render(<App />, document.getElementById('app'))
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
我想更新<Buttons /> 状态,每次单击其中一个按钮时将计数加一。这应该运行 setState() 来更新组件并运行 componentDidUpdate() 函数。问题是,upOne() 函数运行了,但它没有更新组件,因此没有运行 componentDidUpdate() 函数,我不知道为什么。
如果我摆脱 Array.map() 逻辑并使其成为这样的静态函数:
class Buttons extends React.Component {
state = {
variableState,
count: 0,
chosen: 0,
}
upOne = x => {
this.setState(prevState => ({
count: prevState.count + 1,
chosen: x,
}))
console.log('running')
}
componentDidUpdate() {
console.log('componentupdated')
}
render() {
const {variableState, count, chosen} = this.state
const {upOne} = this
return (
<button onClick={() => upOne(1)}>click</button>
)
}
}
它按我的预期工作。
这是预期的行为还是我错过了什么?
【问题讨论】:
-
我已将您的代码放入 sn-p 中,当它运行时,单击按钮显然会尝试重新渲染,但它当然会失败,因为
count现在是1和variableState里面只有一个条目...
标签: javascript reactjs