Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 提交的数据在未刷新的情况下不呈现-react_Reactjs - Fatal编程技术网

Reactjs 提交的数据在未刷新的情况下不呈现-react

Reactjs 提交的数据在未刷新的情况下不呈现-react,reactjs,Reactjs,我从react开始,创建了一个组件,将数据添加到我的数据库中,并保存数据,但是如果不刷新,UI不会更新。我错过了什么 我创建的第一个组件是一个搜索组件,它实际上也执行数据的主要迭代和呈现,这非常有效。然而,新的数据组件给我带来了麻烦 任何帮助都将不胜感激 ================当前主要部件======== class Fruits extends React.Component { constructor(props) { super(props); this.

我从react开始,创建了一个组件,将数据添加到我的数据库中,并保存数据,但是如果不刷新,UI不会更新。我错过了什么

我创建的第一个组件是一个搜索组件,它实际上也执行数据的主要迭代和呈现,这非常有效。然而,新的数据组件给我带来了麻烦

任何帮助都将不胜感激

================当前主要部件========

class Fruits extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      term: '',
      filtered: [],
      itemSelected: {},
      showItemSelected: false
    };
    this.handleSearch = this.handleSearch.bind(this);
    fetch('http://localhost:3000/api/v1/fruits/search?query=' + this.state.term)
    .then((response) => {return response.json()})
    .then((data) => {this.setState({ filtered: data }) });
  }

  handleSearch(e){
    this.setState({
      term: e.target.value
    }, () => {
      fetch('http://localhost:3000/api/v1/fruits/search?query=' + this.state.term)
    .then((response) => {return response.json()})
    .then((data) => {this.setState({ filtered: data }) });
  }).catch(error => {
      console.log('Error fetching and parsing data', error);
    });
  }

  render(){
    let autoCompleteList = this.state.filtered.map((response, index) => {
      return (
      <tr key={index}>
        <td>{response.name}</td>
        <td>{response.description}</td>
        <td></td>
      </tr>
      )
    });
    return (
      <div>
        <AddFruit handleSubmit={this.handleSubmit}/>
        <input ref={ (input) => { this.searchBar = input } } value={ this.state.term } onChange={ this.handleSearch } className="form-control col-md-4" type='text' placeholder='Search...' />
        <table className="table">
          <thead>
            <tr>
              <th>Fruit Name</th>
              <th>Description</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          { autoCompleteList }
          </tbody> 
        </table>
      </div>
  )
  }
}
class AddFruit extends React.Component {

    constructor(props) {
        super(props);
        this.initialState = { name: '', description: '' };
        this.state = this.initialState;
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const { name, value } = event.target;
        this.setState({
            [name] : value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
        fetch('http://localhost:3000/api/v1/fruits', {
            method: 'POST',
            body:   JSON.stringify({
                name: this.state.name,
                description: this.state.description
            }),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        }).then(response => {
                if(response.status === 200) {
                    this.setState(this.initialState);
                }
        }); 
    }
    render() {
        return (
            <div>
                <form className="form-inline" onSubmit={this.handleSubmit}>
                    <input type="text" name="name" className="form-control mb-2" value={this.state.name} onChange={this.handleChange} placeholder="Name"/>
                    <input type="text" name="description" className="form-control mx-sm-3 mb-2" value={this.state.description} onChange={this.handleChange} placeholder="Description"/>
                    <input className="btn btn-primary mb-2" type="submit"  value="Submit" />
                </form>
            </div>
        )
    }

}
class.Component{
建造师(道具){
超级(道具);
此.state={
术语:“”,
已筛选:[],
已选择项:{},
showItemSelected:false
};
this.handleSearch=this.handleSearch.bind(this);
取('http://localhost:3000/api/v1/fruits/search?query=“+this.state.term)
.then((response)=>{return response.json()})
.then((数据)=>{this.setState({filtered:data})});
}
handleSearch(e){
这是我的国家({
术语:目标值
}, () => {
取('http://localhost:3000/api/v1/fruits/search?query=“+this.state.term)
.then((response)=>{return response.json()})
.then((数据)=>{this.setState({filtered:data})});
}).catch(错误=>{
log('Error fetching and parsing data',Error);
});
}
render(){
让autoCompleteList=this.state.filtered.map((响应,索引)=>{
返回(
{response.name}
{response.description}
)
});
返回(
{this.searchBar=input}}value={this.state.term}onChange={this.handleSearch}className=“表单控制col-md-4”type='text'占位符='Search…'/>
果名
描述
行动
{自动完成列表}
)
}
}
===================新数据组件========

class Fruits extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      term: '',
      filtered: [],
      itemSelected: {},
      showItemSelected: false
    };
    this.handleSearch = this.handleSearch.bind(this);
    fetch('http://localhost:3000/api/v1/fruits/search?query=' + this.state.term)
    .then((response) => {return response.json()})
    .then((data) => {this.setState({ filtered: data }) });
  }

  handleSearch(e){
    this.setState({
      term: e.target.value
    }, () => {
      fetch('http://localhost:3000/api/v1/fruits/search?query=' + this.state.term)
    .then((response) => {return response.json()})
    .then((data) => {this.setState({ filtered: data }) });
  }).catch(error => {
      console.log('Error fetching and parsing data', error);
    });
  }

  render(){
    let autoCompleteList = this.state.filtered.map((response, index) => {
      return (
      <tr key={index}>
        <td>{response.name}</td>
        <td>{response.description}</td>
        <td></td>
      </tr>
      )
    });
    return (
      <div>
        <AddFruit handleSubmit={this.handleSubmit}/>
        <input ref={ (input) => { this.searchBar = input } } value={ this.state.term } onChange={ this.handleSearch } className="form-control col-md-4" type='text' placeholder='Search...' />
        <table className="table">
          <thead>
            <tr>
              <th>Fruit Name</th>
              <th>Description</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          { autoCompleteList }
          </tbody> 
        </table>
      </div>
  )
  }
}
class AddFruit extends React.Component {

    constructor(props) {
        super(props);
        this.initialState = { name: '', description: '' };
        this.state = this.initialState;
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const { name, value } = event.target;
        this.setState({
            [name] : value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
        fetch('http://localhost:3000/api/v1/fruits', {
            method: 'POST',
            body:   JSON.stringify({
                name: this.state.name,
                description: this.state.description
            }),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        }).then(response => {
                if(response.status === 200) {
                    this.setState(this.initialState);
                }
        }); 
    }
    render() {
        return (
            <div>
                <form className="form-inline" onSubmit={this.handleSubmit}>
                    <input type="text" name="name" className="form-control mb-2" value={this.state.name} onChange={this.handleChange} placeholder="Name"/>
                    <input type="text" name="description" className="form-control mx-sm-3 mb-2" value={this.state.description} onChange={this.handleChange} placeholder="Description"/>
                    <input className="btn btn-primary mb-2" type="submit"  value="Submit" />
                </form>
            </div>
        )
    }

}
类addreact.Component{ 建造师(道具){ 超级(道具); this.initialState={name:'',description:''}; this.state=this.initialState; this.handleChange=this.handleChange.bind(this); this.handleSubmit=this.handleSubmit.bind(this); } 手变(活动){ 常量{name,value}=event.target; 这是我的国家({ [名称]:值 }); } handleSubmit(事件){ event.preventDefault(); 取('http://localhost:3000/api/v1/fruits', { 方法:“POST”, 正文:JSON.stringify({ 名称:this.state.name, description:this.state.description }), 标题:{ “内容类型”:“应用程序/json;字符集=UTF-8” } })。然后(响应=>{ 如果(response.status==200){ this.setState(this.initialState); } }); } render(){ 返回( ) } }
有些地方需要改进:-

1) 您正在调用
,但您正在
AddFruit
组件本身中定义
handleSubmit
,而不是
Fruits
组件。您可以在水果中定义handleSubmit组件来完成这项工作,或者如果您想在AddFruit中定义handleSubmit,那么请执行以下步骤

2) 添加新水果后,应通知父组件再次获取水果

3) 您应该在componentDidMount中调用fetch fruits,而不是构造函数。更好地创建新功能

fetchFruits () => {
    fetch('http://localhost:3000/api/v1/fruits/search?query=' + this.state.term)
    .then((response) => {return response.json()})
    .then((data) => {this.setState({ filtered: data }) });
}

componentDidMount () {
    this.fetchFruits()
}

addFruitCallback() = () => {
    this.fetchFruits()
}

<AddFruit addFruitCallback={addFruitCallback} /> // pass callback when fruit is added.
fetchFruits()=>{
取('http://localhost:3000/api/v1/fruits/search?query=“+this.state.term)
.then((response)=>{return response.json()})
.then((数据)=>{this.setState({filtered:data})});
}
组件安装(){
这个
}
addFruitCallback()=()=>{
这个
}
//添加水果时传递回调。

希望有帮助

在从子项发出POST呼叫后,“筛选”状态不会更新。
在handleSubmit中,在POST调用成功后,将其与父级通信,并通过再进行一次API调用来更新“筛选”状态

您可以通过将handleSubmit()函数发送到父组件Fruits来实现这一点,以便将其作为道具传递给子组件addfruit,然后在子组件中调用。您将完全按照此处的方式传递它
,但函数

    handleSubmit(fruitObject) {
        fetch('http://localhost:3000/api/v1/fruits', {
            method: 'POST',
            body:   JSON.stringify(fruitObject),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        }).then((response) => {return response.json()})
          .then((fruit) => {this.setState({ filtered: [...this.state.filtered, fruit] })
           }); 
    }

 will be inside of  Fruit component.

So inside of your AddFruit Component You just need to call this function 
that was passed as props to it with the fruit you want to add.
Aso that is supposing that your API returns the Added fruit after adding it to the database.

您是否在保存后再次从服务器获取数据???我在提交后重置表单。请原谅我的无知,但提交后重新获取数据的最佳方式是什么?将函数作为道具从家长传递给孩子以获取数据,并在成功调用itThanks后,调用itThanks,这就成功了,我可以从@tarzen chughThanks获得提示,这让我得到了排序。