Laravel/React - 从控制器获取数据数组以响应组件
我的案例:
我正在将 Laravel (laravel/ui 脚手架)和 React App 结合起来。 这是我第一次尝试这个,发现自己陷入了从 BE 到 FE 获取数据的困境。
我看起来正在获取数据,但是当从该元素的数据集中记录时,我的 $testData 数组被转换为字符串。我不确定我应该做什么才能拥有我的数组恢复为 json 格式。
代码:
发送数据的控制器:
public function index()
{
$testData = [
["name" => "Lucy"],
["name" => "Kurt"],
["name" => "Emma"],
];
return view('intern.index')->with('testData', $testData);
}
我有我的刀片,正在加载具有特定id的div:
@extends('layouts.app')
@section('body')
<div id="react-app" data-list={{ json_encode($testData) }} ></div>
@endsection
以及在刀片视图上呈现的我的反应组件app.js :
function App( props ) {
console.log(props.list)
return (
<div className="container">
Hello World!
</div>
);
}
export default App;
if (document.getElementById('react-app')) {
const thisElement = document.getElementById('react-app');
let props = Object.assign({}, thisElement.dataset);
console.log(props)
/* The restult I am getting from that log:
{
list: "{{\"name\":\"Lucy\"},{\"name\":\"Kurt\"},{\"name\":\"Emma\"}}"
}
*/
ReactDOM.render(<App list={props.list} />, thisElement);
}
My case:
I am combining Laravel (laravel/ui scaffolding) and React App.
This is my first time trying this, and found myself stuck in getting data from BE to FE.I Looks like I am getting the data, but my array of $testData is converted into a string When being logged from the Dataset of that element. I am not sure what I should do to have my array back to a json format instead.
the code:
A Controller sending my data:
public function index()
{
$testData = [
["name" => "Lucy"],
["name" => "Kurt"],
["name" => "Emma"],
];
return view('intern.index')->with('testData', $testData);
}
I have my blade, loading a div with a certain id:
@extends('layouts.app')
@section('body')
<div id="react-app" data-list={{ json_encode($testData) }} ></div>
@endsection
And my react component app.js that is rendered on the blade view:
function App( props ) {
console.log(props.list)
return (
<div className="container">
Hello World!
</div>
);
}
export default App;
if (document.getElementById('react-app')) {
const thisElement = document.getElementById('react-app');
let props = Object.assign({}, thisElement.dataset);
console.log(props)
/* The restult I am getting from that log:
{
list: "{{\"name\":\"Lucy\"},{\"name\":\"Kurt\"},{\"name\":\"Emma\"}}"
}
*/
ReactDOM.render(<App list={props.list} />, thisElement);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新:
解决方案是简单地解析结果。
Update:
The solution was to simply parse the result back.