React on Rails应用程序很新,尤其是React部分。我正在尝试访问Rails服务中SQL查询提供的嵌套哈希中的数据。首先,这有可能吗?
在Rails控制台中,假设id已找到user1,即LedgersService.transactions(user1)。首先以这种格式返回所有数据:
{:transactable => {:type =>“存款”, :id =>“ 28cba04f-5b9d-4c9c-afca-b09a6e0e8739”, :user_id =>“ 72700244-e6b0-4baf-a381-c22bfe56b022”, :transacted_at =>“ 2019-03-12 19:04:48.715678”,:amount_cents => 15, :notes =>“ none”,:processor => nil,:details => nil}, :ledgers => [{{:entry_type =>“ credit”,:amount_cents => 15, :transacted_at =>“ 2019-03-12 19:04:48.715678”, :user_id =>“ 72700244-e6b0-4baf-a381-c22bfe56b022”, :transactable_type =>“存款”, :transactable_id =>“ 28cba04f-5b9d-4c9c-afca-b09a6e0e8739”}]}
我正在尝试在我的React组件中执行类似的操作来尝试获取数据,但是,我不确定如何设置LedgersService.transactions部分。这是我目前的情况:
class LedgersIndex extends React.Component {
constructor(props) {
super(props);
this.state = { ledgers_service: { transactions: [] }, paginator: { count: 0, page: 0, limit: 0 }, user: { id: this.props.match.params.user_id } };
我的端点呼叫:
componentDidMount() {
var user_id = this.state.user.id;
this.fetchData(user_id, 1);
}
fetchData = (user_id, page_number) => {
apiService.ledgersIndex(user_id, page_number)
.then(
paginated => {
this.setState({
ledgers_service: {
transactions: paginated.ledgers_service.transactions
},
paginator: {
limit: paginated.meta.limit,
count: paginated.meta.count,
page: paginated.meta.page -1
}
});
},
进一步渲染:
render() {
const { classes } = this.props;
const { ledgers_service, paginator } = this.state;
我在apiService中获取的信息:
function locationsIndex(page_number) {
const requestOptions = {
method: 'GET',
headers: Object.assign({},
authorizationHeader(),
{ 'Content-Type': 'application/json' })
};
return fetch(`${process.env.API_SERVER}/api/v1/admin/locations?page=${page_number}`, requestOptions)
.then(handleResponse)
.then(paginated => {
return paginated;
});
}
当我console.log(ledgers_service.transactions(this.state.user.id))时,出现错误消息ledgers_service.transactions不是函数。 console.log(paginator.count)起作用了,这是因为将事务设置为数组吗?
在Rails控制台中获得React组件中相同端点的正确方法是什么?
答案 0 :(得分:0)
React on Rails应用程序很新,尤其是React部分。我是 尝试访问SQL查询给出的嵌套哈希中的数据 在Rails服务中。
是的,JS喜欢 JSON ,因此您应该有一个用JSON响应的Rails操作。这是在React和Rails之间交换数据的正确方法:
# in your React app
fetch('/path/to/resource.json')
.then((returnedResource) => {
// do something with JSON
})
.catch(error => console.error('Error:', error));
# in your controller
respond_to do |format|
format.json { render json: LedgersService.transactions(user1).first }
end
从那里,您可以将returnedResource
视为JSON对象。您的情况是pagination