我正在为前端和后端节点进行自我项目React,该应用程序的一部分是,当用户提交图像url时,它会计数条目并在服务器中更新,然后应该重新-渲染到屏幕的前端。问题是它不会重新渲染,我已经对console.log进行了测试,并且一切都可以从服务器端运行,问题是在setState中,反应不会重新渲染,我希望有人能帮助我理解为什么不工作吗?
这是与我的问题有关的代码
class App extends Component {
constructor() {
super()
this.state = {
input: '',
imgUrl: '',
box: {},
route: 'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: '',
},
}
}
loadUser = data => {
this.setState({
user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined,
},
})
}
onButtonSubmit = () => {
fetch('http://localhost:3001/image', {
method: 'put',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: this.state.user.id,
}),
})
.then(response => response.json)
.then(count => {
this.setState({ ...this.state.user, entries: count })
})
.catch(err => console.log(err))
}
}
render() {
return (
<div className="App">
<Navigation
isSignedIn={this.state.isSignedIn}
onRouteChange={this.onRouteChange}
/>
{this.state.route === 'home' ? (
<div>
<Rank
name={this.state.user.name}
entries={this.state.user.entries}
/>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}
/>
<FaceRecognition box={this.state.box} imgUrl={this.state.imgUrl} />
</div>
) : this.state.route === 'signin' ? (
<Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
) : (
<Register
loadUser={this.loadUser}
onRouteChange={this.onRouteChange}
/>
)}
</div>
)
}
此代码假设是在屏幕上打印条目计数,但不是
this.setState({...this.state.user, entries: count})
这是服务器端,条目将被更新并发送到前端
app.put('/image', (req, res) => {
const { id } = req.body
let found = false
database.users.forEach(user => {
if (user.id === id) {
found = true
user.entries++
return res.json(user.entries)
}
})
if (!found) {
res.status(400).json('not found')
}
})
这是打印条目的等级组件
import React from 'react';
const Rank = ({ name, entries}) => {
return (
<div>
<div className='rank'>
{`${name} your current rank is...`}
</div>
<div className='white f1 '>
{entries}
</div>
</div>
);
}
export default Rank;
谢谢。
答案 0 :(得分:1)
我看不到在setState中执行... this.state.user的任何用途
更改
this.setState({...this.state.user, entries: count})
收件人
this.setState({entries: count})