我如何在axios请求中输入ID以从后端提取特定数据

时间:2019-04-23 02:53:02

标签: reactjs postgresql react-redux axios

好的,这里有点新。 因此,当前我在后端中有数据,需要使用特定的ID将其提取,以便它获取该用户的特定数据。在后端,我只需要将其作为参数即可。在前端,我能够提取需要输入参数的所有者“ ID”,我只是不知道我是否正在执行此操作,这是我的前端和服务器控制器代码。这是我的日志的图片16是我使用enter image description here

的特定用户的代码

class GetDogs extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: "",
      dogs: []
    };
  }
  async componentDidMount() {
    //destructure get user function
    const { getUser } = this.props;
    //call function to get user info
    await getUser();
    //sets state into owner_id that i need to be put as the argument for my get dog's function
    await this.setState({ id: this.props.userReducer.user.owner_id });
    //call axios to bring dog info
    await axios
      .get(`/api/yourdogs`, {
        owner_id: this.state.id
      })
      .then(response => {
        this.setState({ dogs: response.data });
      });
  }
  render() {
    console.log(this.state.id);
    console.log(this.state.dogs);
    return <div>get dogs</div>;
  }
}
const mapStateToProps = state => state;

export default connect(
  mapStateToProps,
  { getUser }
)(GetDogs);
module.exports = {
  newDog(req, res) {
    const db = req.app.get("db");
    const { name, age, picture, breed, sex, owner_id } = req.body;
    db.newDog([name, age, picture, breed, sex, owner_id])
      .then(response => {
        res.status(200).send(response);
      })
      .catch(console.log);
  },
  getDogs(req, res) {
    const db = req.app.get("db");
    const { owner_id } = req.body;
    db.getDogs([owner_id])
      .then(response => res.status(200).json(response))
      .catch(console.log);
  }
};

1 个答案:

答案 0 :(得分:0)

而不是这样:

...
    await this.setState({ id: this.props.userReducer.user.owner_id });
    //call axios to bring dog info
    await axios
      .get(`/api/yourdogs`, {
        owner_id: this.state.id // i don't think this.state.id is already assign new value
      })
      .then(response => {
        this.setState({ dogs: response.data });
      });
...

所以,尝试这样:

...
  this.setState({ id: this.props.userReducer.user.owner_id }, () => {
    //call axios to bring dog info
    axios
      .get(`/api/yourdogs`, {
        owner_id: this.state.id
      })
      .then(response => {
        this.setState({ dogs: response.data });
      });
  });
...