我最近开始尝试使用 React 并尝试突破界限(至少在我看来它看起来很神奇)。
我正在尝试使用动态数据结构创建一个发布到预定义 API 的组件,即我想将数据参数作为 Prop 传递。这是我当前的 AJAX 代码示例:
createModalSubmit(form) {
var name = this.refs.name.value;
$.ajax({
url: `/items.json`,
type: 'POST',
data: item:{name: name} ,
success: (item) => {
this.setState({
item: {
name: ''
},
errors: {},
showModal: false
});
},
error: (item) => {
this.setState({errors: item.responseJSON.errors})
}
});
},
如何在这部分代码中将数据属性作为 Prop 传递?我尝试将其作为一个函数来执行,即:
formData() {
return {
myData: {
item: {
name: name
}
}
}
},
然后将它作为“this.formData”传递给我的数据属性,但这似乎并没有带来快乐。
我也尝试过使用 vars,但上面的函数式方法对我来说最有意义。
将动态值传递给 ajax js 调用的最佳方式是什么?
最佳答案
这是一个示例,说明如何将动态值传递给 React 中的 ajax 调用:http://codepen.io/PiotrBerebecki/pen/ZpRyKb
在示例中,父组件 App
正在维护一个包含 url 的对象的状态。然后,父组件通过 props 向其子组件(Time
和 Photo
)提供单独的 url。
完整代码如下:
class App extends React.Component {
constructor() {
super();
this.state = {
urls: {
time: 'http://date.jsontest.com',
photos: 'http://jsonplaceholder.typicode.com/photos'
}
};
}
render() {
return (
<div>
<Time url={this.state.urls.time} />
<Photo url={this.state.urls.photos} />
</div>
);
}
}
class Time extends React.Component {
constructor() {
super();
this.state = {
data: null
};
}
componentDidMount() {
$.ajax({
type: "GET",
url: this.props.url,
success: (response) => {
this.setState({
data: response.time,
});
}
});
}
render() {
let content;
if (this.state.data) {
content = (
<div>
<h1>Current Time</h1>
<p>{this.state.data}</p>
</div>
);
} else {
content = <div>Loading...</div>;
}
return (
<div>
{content}
</div>
);
}
}
class Photo extends React.Component {
constructor() {
super();
this.state = {
data: null
};
}
componentDidMount() {
$.ajax({
type: "GET",
url: this.props.url,
success: (response) => {
this.setState({
data: response,
});
}
});
}
render() {
let content;
if (this.state.data) {
content = (
<div>
<h1>Photo</h1>
<img src={this.state.data[0].url}/>
</div>
);
} else {
content = <div>Loading...</div>;
}
return (
<div>
{content}
</div>
);
}
}
ReactDOM.render(
<App />, document.getElementById('content')
);
关于javascript - 在 AJAX js 调用中动态分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007489/