所以我有两个数组。一个装满内容,一个装满内容。当前有效的是,使用onClick函数,我将第一个数组中的值拼接起来并将其推入第二个数组中。
一切正常(使用console.log测试)。但是我在第二堂课中渲染的数组不会更新
export class OpeningHoursContent extends Component {
constructor (props) {
super (props)
this.state = {
OpeningHoursUsed : [],
OpeningHoursOptions : [
{value: 'open247', option: 'Open 24/7', title: 'Open 24/7', content: 'We are open 24/7'},
{value: 'openClosed', option: 'Open / Closed', title: 'Open / Closed', content: '<OpeningHoursTable />'},
{value: 'holidays', option: 'Holidays', title: 'Holidays', content: '<ListHolidays />'},
{value: 'showroom', option: 'Showroom', title: 'Showroom', content: '<OpeningHoursTable />'},
{value: 'shop', option: 'Shop', title: 'Shop', content: '<OpeningHoursTable />'},
{value: 'office', option: 'Office', title: 'Office', content: '<OpeningHoursTable />'},
{value: 'deskoffice', option: 'Deskoffice', title: 'Deskoffice', content: '<OpeningHoursTable />'},
{value: 'workspace', option: 'Workspace', title: 'Workspace', content: '<OpeningHoursTable />'},
{value: 'vacation', option: 'Vacation', title: 'Vacation', content: '<ListVacation />'},
{value: 'appointment', option: 'Appointment', title: 'Appointment', content: '<OpeningHoursTable />'},
{value: 'selfservice', option: 'Selfservice', title: 'Selfservice', content: '<OpeningHoursTable />'},
{value: 'addMessage', option: 'Add a message', title: 'Your message', content: '<OpeningHoursTable />'},
{value: 'addCustom', option: 'Add custom', title: 'Custom title', content: '<OpeningHoursTable />'}
]
}
}
UpdateOpeningHoursUsed ({ value, option, title, content }, index) {
this.state.OpeningHoursUsed.push({ value: value, option: option, title: title, content: content })
this.state.OpeningHoursOptions.splice(index, 1);
}
render () {
return (
this.state.OpeningHoursOptions.map(({ value, option, title, content }) => {
return (
<div key={value} onClick={() => this.UpdateOpeningHoursUsed({ value, option, title, content })} className='option'>{option}</div>
);
})
)
}
}
export default class EditOpeningHours extends Component {
render () {
return (
<div>
// THIS PART SHOULD RERENDER AFTER SPLICE
<OpeningHoursContent />
</div>
);
}
}
答案 0 :(得分:1)
请勿更改状态,请使用setState更新状态。使用setState还将触发重新渲染,使您可以在渲染中查看更新的数据
UpdateOpeningHoursUsed ({ value, option, title, content }, index) {
this.setState(state => {
const updated = state.OpeningHoursUsed.concat([{ value: value, option: option, title: title, content: content }])
return {
OpeningHoursUsed: updated,
OpeningHoursOptions: updated.splice(index, 1)
}
})
}
答案 1 :(得分:0)
React没有双向绑定,因此您需要使用setState
UpdateOpeningHoursUsed ({ value, option, title, content }, index) {
this.state.OpeningHoursUsed.push({ value: value, option: option, title: title, content: content })
this.state.OpeningHoursOptions.splice(index, 1);
this.setState({OpeningHoursUsed, OpeningHoursOptions});
}