我正在使用带有React的Typescript尝试(以前从未使用过)。我解决了一个问题,但是我不确定这是否是正确的方法。
所以我的反应路线看起来像这样
<Route exact path='/show/:id' component={ShowIssues} />
我解决的组件看起来像这样
import React from "react";
import { RouteProps } from "react-router-dom";
interface RouteInfo extends RouteProps {
params: {
id: string;
};
}
const ShowIssues = ({ match }: { match: RouteInfo }) => {
const { params }: { params: { id: string } } = match;
const { id }: { id: string } = params;
return <div>time to show the issue {id}</div>;
};
export default ShowIssues;
在这场比赛的道具中正确解决了吗?令人惊讶的是,我几乎没有发现有关功能组件的任何东西(并且钩子已经来临,所以我想提出这个疑问是有道理的。)
我对const { params }: { params: { id: string } } = match;
的另一个疑问是,有没有一种方法可以重用RouteInfo
,所以我不必两次输入?
谢谢!
答案 0 :(得分:1)
func Create(w http.ResponseWriter, r *http.Request) {
var p Page //Create an instance of our struct
//Read all the data in r.Body from a byte[], convert it to a string, and assign store it in 's'.
s, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err) // This would normally be a normal Error http response but I've put this here so it's easy for you to test.
}
// use the built in Unmarshal function to put the string we got above into the empty page we created at the top. Notice the &p. The & is important, if you don't understand it go and do the 'Tour of Go' again.
err = json.Unmarshal(s, &p)
if err != nil {
panic(err) // This would normally be a normal Error http response but I've put this here so it's easy for you to test.
}
// From here you have a proper Page object which is filled. Do what you want with it.
render.JSON(w, r, p) // This is me using a useful helper function from go-chi which 'Marshals' a struct to a json string and returns it to using the http.ResponseWriter.
}
和Decoder
类型是多余的,因为如果正确键入const { params }: { params: { id: string } }
会推断出它们。
路线道具是具有const { id }: { id: string }
属性match
的特定类型的对象。它接受match
类型作为通用参数。
应该是:
RouteComponentProps