gpt4 book ai didi

reactjs - React 组件自动重新渲染到它的初始状态

转载 作者:行者123 更新时间:2023-12-05 09:17:21 27 4
gpt4 key购买 nike

我正在制作一个简单的 React 测试应用程序。

什么是应用程序:它显示项目的名称,并有添加新项目的选项。每个项目都有标题和类别。

原来是这样

enter image description here

问题:当我尝试通过输入标题然后单击提交按钮来添加新项目时,新项目名称出现在项目中几秒钟然后消失。项目列表回到初始状态,即三个项目(如下所示)

这是代码

App.js

import React, { Component } from 'react';

import './App.css';
import Projects from "./Components/Projects"
import AddProjects from './Components/AddProject'

class App extends Component {
constructor(){
super();
this.state = {
projects:[]
}
}

componentWillMount(){
this.setState({projects:[
{
title: "Trigger",
category: "Web App"
},
{
title: "Trigger",
category: "Web App"
},
{
title: "Trigger",
category: "Web App"
}
]})
}

handleAddProject(project){
let projects = this.state.projects;
projects.push(project)
this.setState({projects:projects})
console.log(this.state.projects)
}

render() {
return (
<div className="App">
My Project
<AddProjects addProject={this.handleAddProject.bind(this)}/>
<Projects projects={this.state.projects}/>
</div>
);
}
}

export default App;

项目.js

import React, { Component } from 'react';
import Projectitem from './ProjectItem'


class Projects extends Component {

render() {
let projectItems
if(this.props.projects){
projectItems = this.props.projects.map(project =>{
return (
<Projectitem project={project}/>
);
})
}
else{
console.log("hello")
}

return (
<div>
This is a list of objects
{projectItems}
</div>
);
}
}

export default Projects

ProjectItem.js

import React, { Component } from 'react';


class ProjectItem extends Component {
render() {
return (

<li>
{this.props.project.title}:{this.props.project.category}
</li>

);
}
}

export default ProjectItem

添加项目.js

import React, { Component } from 'react';


var categories = ["Web dev", "Mobile dev", "websiite"]

class AddProject extends Component {
constructor(){
super();
this.state = {
newProject:{}
}
}


handleSubmit(){
this.setState({newProject:{
title:this.refs.title.value,
category:this.refs.category.value
}}, function () {
this.props.addProject(this.state.newProject)
})
}
render() {
var categoryOptions = categories.map(category=>{
return <option key={category} value={category}>{category}</option>
})
return (
<div>
Add Project <br/>
<form onSubmit={this.handleSubmit.bind(this)}>
<div>
<label>title</label><br/>
<input type="text" ref="title"/>
</div>
<div>
<label>Category</label><br/>
<select ref="category">
{categoryOptions}
</select>
</div>
<input type="submit" value="Submit"/>
</form>
</div>

);
}
}

export default AddProject

最佳答案

event.preventDefault() 添加到您的 handleSubmit() 方法

handleSubmit(event) {
event.preventDefault();
alert('A name was submitted: ' + this.state.value);
}

没有它,您的页面将刷新(就像提交表单时的默认情况一样)

关于reactjs - React 组件自动重新渲染到它的初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48324874/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com