React Native中URL拼接State变量失败问题求助
Hey there, no worries at all—every developer starts somewhere, and this is a super common gotcha with JavaScript template strings! Let's break down what's going wrong here and fix it step by step.
核心问题:模板字符串的引号使用错误
Looking at your fetch call, you wrapped the URL in single quotes ('), but JavaScript's template literal syntax (the ${variable} part you're using) only works when you wrap the string in backticks (`), not single or double quotes.
Right now, your API is receiving the literal string class=${this.state.classid} instead of the actual value stored in this.state.classid. That's why hardcoding works (you're sending a real value), but using variables returns "NO records found"—the API can't match those literal placeholder strings to any data.
次要问题:URL中的多余空格
You also have an extra space after the ? in your URL (? class=). This will make your parameter name class (with a leading space), which the API almost certainly doesn't expect. You'll need to remove that space to make the parameter name valid.
额外建议:正确更新React State
You're directly assigning values to this.state like this.state.secid = ...—while this might work for your current use case, React recommends using this.setState() to update state. Directly modifying this.state doesn't trigger component re-renders and can lead to unexpected behavior later on.
修正后的代码
Here's your code with all the fixes applied:
// Update state correctly with setState this.setState({ secid: this.props.navigation.state.params.secid, classid: this.props.navigation.state.params.clasid }, () => { // Make the fetch call after state is updated (optional but safe) console.log(this.state.secid); console.log(this.state.classid); // Sending Request with fixed URL syntax fetch(`exampleapi/parameter?class=${this.state.classid}§ion=${this.state.secid}`, { headers: { 'Content-Type':'application/json', 'credentials': 'same-origin', 'Accept': 'application/json', 'Authorization': 'Bearer ' + tokenval } }) .then((response) => response.json()) .then((responseJson) => { this.setState({ allstudents : responseJson }); console.log(this.state.allstudents); }); });
为什么这能解决问题?
- Using backticks around the URL lets JavaScript replace
${this.state.classid}and${this.state.secid}with their actual values, so the API gets valid parameters. - Removing the space after
?ensures the parameter names (classandsection) match what the API expects. - Using
this.setState()ensures state is updated properly and any dependent logic (like the fetch call) runs after the state changes.
内容的提问来源于stack exchange,提问作者Zuha Karim

