React项目中提交新fortune后无法通过splice/push加入目标数组问题求助
问题原因
1. Fortune组件语法错误
你当前Fortune组件的state定义存在严重语法错误,array.push、array.splice这三行代码直接写在了state对象内部,不符合JS对象的定义规则,首先要删掉这三行错误代码,修正后的constructor基础结构如下:
constructor(props) { super(props); this.state = { fortunes: [ "An exciting opporunity lies ahead", "A long time friend will brirng wise advice in the coming week", "You will find great fortunes in unexpected places", "Never give up... Unless you want to thats cool too", "111", "222", "333", "444", "Maybe a nap is what you need", "Don't Text Your EX!" ], fortune: "" } }
2. 两个组件数据未连通
你当前的AddFortune组件提交成功后只做了路由跳转,没有把新提交的签文内容同步给Fortune组件,也没有更新Fortune组件的fortunes数组,自然没法看到新增的内容。
修复方案
这里提供两种常用的实现方式,按需选择即可:
方案一:从后端拉取全量签文(推荐)
你已经把新签文提交到了后端接口,最合理的方式是让Fortune组件在加载时直接从后端拉取所有的签文数据,而不是只写死本地数组:
- 给
Fortune组件新增拉取全量签文的方法:
componentDidMount() { // 先拉取后端所有签文 this.fetchAllFortunes(); } fetchAllFortunes = () => { fetch("https://backend-edwin.herokuapp.com/item/list") // 替换为你的后端全量查询接口 .then(res => res.json()) .then(data => { // 把后端返回的签文和本地默认数组合并,或者直接覆盖 this.setState({ fortunes: [...this.state.fortunes, ...data.map(item => item.name)] }, () => { // 拉取完成后再获取随机签文 this.getFortune(); }) }) .catch(err => console.log("拉取签文失败", err)) }
这种方式刷新页面后新增的签文也不会丢失,是持久化存储的正确做法。
方案二:路由跳转时传值
如果暂时不想改后端,可以在AddFortune提交成功跳转的时候把新签文带到Fortune页面:
- 修改
AddFortune的提交成功逻辑:
.then(data => { if (data.id) { // 跳转时把新签文通过路由state传递 this.props.history.push({ pathname: "/fortune", state: { newFortune: this.state.nameInput } }) } })
- 在
Fortune组件中接收路由传的新签文,加入数组:
componentDidMount() { // 检查路由是否带了新签文 if(this.props.location.state?.newFortune) { this.setState(prev => ({ fortunes: [...prev.fortunes, this.props.location.state.newFortune] })) } this.getFortune(); }
这种方式的缺点是刷新页面后新增的签文会丢失,只存在单次跳转的状态里。
内容的提问来源于stack exchange,提问作者Eddy10
相关产品推荐
相关产品推荐

