我试图动态地从表单中收集输入数据,而不是键入每个单独的输入字段名称。使用标准React,这很容易,但是我要切换到React Hooks,现在我对如何实现相同目标有些困惑。
const gatherFormData = e => {
if (e.target.value !== null) {
_.assign(
formData.payload,
{ [e.target.name]: e.target.value, action },
{ groupNumber },
);
setState({
[e.target.name]: (e.target.value),
formData
});
}
};
我尝试使用模板文字语法,但这没用。
set`${e.target.name}`(e.target.value);
答案 0 :(得分:0)
您可以将useState
与对象配合使用,以使其可以动态添加内容。示例:
const [targets, setTargets] = useState({});
// Set values like this
setTargets({...targets, [`${e.target.name}`]: e.target.value});
// Then get values:
const theValue = targets.yourTargetNameHere
设置值时,必须使用spread syntax({...targets
)来保持放置在对象中的其他值。
答案 1 :(得分:0)
private void readFromServer() throws Throwable {
String testSite = "https://sites.google.com/site/myName/test.txt";
HttpURLConnection urlConn = getFile(testSite);
InputStream inStream = urlConn.getInputStream();
doSomethingWith(inStream);
inStream.close();
urlConn.disconnect();
}
private static HttpURLConnection getFile(String testSite) throws Throwable {
HttpURLConnection.setFollowRedirects(false);
URL txtUrl = new URL(testSite);
HttpURLConnection urlConn = (HttpURLConnection)txtUrl.openConnection();
int timeout = 15000;
urlConn.setConnectTimeout(timeout); //15 seconds
urlConn.setReadTimeout(timeout);
urlConn.setAllowUserInteraction(false);
urlConn.setDoOutput(false);
urlConn.setInstanceFollowRedirects(false);
//Log.v(TAG, "Request URL ... " + txtUrl);
urlConn = handleRedirects(urlConn, testSite);
return urlConn;
}
private static HttpURLConnection handleRedirects(HttpURLConnection urlConn, String testSite) throws Throwable
{
final int maxRedirect = 10;
int numRedirect = 0;
boolean isRedirect;
String referer = testSite;
do {
isRedirect = mustRedirect(urlConn);
if (isRedirect) {
String newAddress = urlConn.getHeaderField("Location");
String cookies = urlConn.getHeaderField("Set-Cookie");
urlConn = (HttpURLConnection) new URL(newAddress).openConnection();
urlConn.setRequestProperty("Cookie", cookies);
urlConn.addRequestProperty("Referer", referer);
referer = newAddress;
numRedirect++;
}
} while (isRedirect && (numRedirect < maxRedirect));
return urlConn;
}
private static boolean mustRedirect(HttpURLConnection urlConn) throws Throwable
{
int status = urlConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
return false;
}
return isMoved(status);
}
private static boolean isMoved(int status) { // normally, 3xx is redirect
return status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER
|| status == -1; //returns -1 instead of 301. (no valid response code)
}