gpt4 book ai didi

javascript - react Axios : How to send just the state value of my prop to backend

转载 作者:行者123 更新时间:2023-11-28 03:08:21 24 4
gpt4 key购买 nike

因此,我已将父状态作为名为 title 的属性传递给子组件。我想使用该 prop 的值向 axios 发出 put 请求。如果我将它渲染在 div 中,它会返回状态值,但是当我将其放入 axios 参数中时,它不会返回。相反,在我的控制台日志中,它显示了一个 prop 对象:

{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
$$typeof: Symbol(react.element)
type: class Title
key: null
ref: null
props: {title: "Godfather"}
_owner: null
_store: {validated: false}
_self: componentData {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …}
_source: {fileName: "C:\Users\Craig\Desktop\project - Copy\client\src\components\Movies\SendingMovie.js", lineNumber: 20}
__proto__: Object

基本上,我只想发送“教父”。不是像上面那样的整个对象。另外,当我为这个子组件创建一个虚拟状态并给它 movie: 'Godfather' 然后将其传递到 axios put 请求中,数据库注册并运行。所以我的后端代码很好但是我不确定为什么 props 不只给我状态值。

缩短的代码片段:

父级(称为食物的组件):

class Votes extends Component {
constructor(props, context) {
super(props, context);
this.state = {
error: null,
isLoaded: false,
foods: [],
activefood:'', //new added
};

...

render() {
const title = this.state.activefood
return(
<p>
title={title}
</p>
)
}

child :

import React, {
Fragment,
useState,
useEffect,
Component
} from "react";
import axios from "axios";
import Votes from './Foods';
import Title from './Title';


export default class SendingFood extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
clicked: false
}
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState({
clicked: true,
});
}


patchFunction() {
this.setState({isLoading: true});
axios.patch('api/food/modify', {foodname: <Title title={this.props.title}/>})
.then(res => {
console.log(res);
this.setState({
isLoading: false,
})
console.log('sent');
},
(error) => {
this.setState({
isLoaded: true,
error

});

}
)
};


combinedFunction() {
this.patchFunction();
this.handleClick();
}

render(){
const {isLoading, error} = this.state;
if (error) {
return <div style={{color: "red"}}>Error: {error.message}</div>;
};
return (
<Fragment>
<Title title={this.props.title}/>
<button className="primary" onClick={() => { this.patchFunction() }}>Submit Vote</button>

</Fragment>
)}
}
<小时/>
import React, {
Fragment,
useState,
useEffect,
Component
} from "react";

export default class Title extends React.Component{
render() {
return (
<Fragment>
{this.props.title}
</Fragment>
);
}
}

到目前为止,我一直在使用 React 来渲染 props 并将数据和状态传递给其他组件,但现在我陷入了我想要子组件接收状态数据并将其发送到后端的困境。也许我使用了错误的程序或错误的工具来完成这项工作?

最佳答案

您能否发布一段代码,说明如何将父级的状态传递给子级?

关于javascript - react Axios : How to send just the state value of my prop to backend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401088/

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