在我的 React Native 应用程序中,我有一个 ProductScreen
,其中导入两个文件来完成屏幕。
文件 1 (Products.js
) 是我的产品列表
文件 2 (Data.js
) 是我的数据文件(只是临时的)
import Products from '../../components/Products';
import { shoes} from '../../Data';
<小时/>
在我的ProdcutScreen
中,我使用导入的Products
作为组件
并将products
的值设置为鞋子
<Products products={shoes} onPress={this.props.addItemToCart}/>
<小时/>
然后在 Product.js
文件中,我尝试将产品列表的 state
设置为产品(在 ProdcutScreen
中调用时)设置为鞋子
)
state = {
products,
filteredProducts: products,
};
<小时/>
这就是问题发挥作用的地方,因为我收到了错误
ReferenceError: ReferenceError: ReferenceError: ReferenceError: Can't find variable: products
问题来自于 Products.js
文件中的第 16 行,即
state = {
products,
filteredProducts: products,
};
因此,从 Data.js
文件收集的 shoes
值似乎没有传递给状态。
我的问题是如何传递这个值?
当我不设置 state
并像这样渲染列表时,列表确实可以工作
{this.renderProducts(this.props.products)}
但我需要设置状态,因为我希望能够过滤我的产品。
<小时/>ProductScreen.js
import { drinks } from '../../Data';
import { connect } from 'react-redux';
export class ProductScreen extends React.Component {
static navigationOptions = {
headerTitle: 'shoes'
}
render() {
return (
<View style={styles.container}>
<Products products={shoes} onPress={this.props.addItemToCart}/>
<View >
{/* <TouchableOpacity style={styles.checkOutContainer} onPress={() => this.props.onPress(item)} >
<Icon style={styles.checkmark} name="ios-checkmark" color="white" size={35} />
</TouchableOpacity> */}
</View>
</View>
)
}
}
<小时/>
Data.js
export const shoes= [
{
id: 1,
name: 'Hurrace',
brand: 'Nike',
type: 'strong',
price: 7,
},
]
<小时/>
产品.js
class Products extends Component {
state = {
products,
filteredProducts: products,
};
setSearchText(event) {
const searchText = event.nativeEvent.text;
const textLength = this.state.products.length;
const filteredTexts = this.state.products.filter(row => {
return row.name.indexOf(searchText) !== -1;
});
console.log("text: " + JSON.stringify(filteredTexts));
this.setState({
searchText,
filteredProducts: filteredTexts
});
}
renderProducts = (products) => {
console.log(products)
return products.map((item, index) => {
return (
<View key={index} style={styles.shoes}>
<View style={styles.text}>
<Text style={styles.name}>
{item.name}
</Text>
<Text style={styles.price}>
€ {item.price}
</Text>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={() => this.props.onPress(item)} >
<Icon style={styles.button} name="ios-add" color="white" size={25} />
</TouchableOpacity>
</View>
</View>
)
})
}
<小时/>
我仍在学习 React Native,几个月前就开始了。
最佳答案
如果您打算使用 props 作为初始值,则不能使用实例属性。您需要通过构造函数(传递 props 的地方)来完成此操作:
class Products extends Component {
constructor(props) {
super(props);
const { products } = this.props;
this.state = {
products,
filteredProducts: products,
};
}
...
关于javascript - ReferenceError 因为变量没有被传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53707642/