私は過去2〜3日間の検索を行いましたが、提案された回答をたくさん試しましたが、答えを理解することができないか、これはできないことです。私は自分のサイトのショッピングカートを構築していて、カートにアイテムを追加し、その更新された数量をカートのアイコンに追加できるようにする必要があります。私はreduxと一緒に試みたが、それが当時のように動作するようにはできなかった。メインファイルにカートを保存し、それを必要なコンポーネントに渡したい。問題は私がやっていることだ。私のaddToCartメソッドが伝承し、私はちょうどそれが私のルートファイルに関数/メソッドを渡すと反応する
addToCart(id) {
axios.get(`http://localhost:8080/add-to-cart/${id}`)
.then(response => {
console.log(response)
}
}
render() {
// const MyProductPage = (props) => {
// return (
// <TestProducts
// addToCart={this.addToCart.bind(this)}
// {...props}
// />
// );
// }
return (
<Router>
<div>
<Header />
<Route exact path='/' component={Home} />
{/* <Route path='/products' render={MyProductPage} /> */}
<Route path="/products" render={props => <TestProducts addToCart = {this.addToCart} {...props} />} />
<Route path='/about-us' component={About} />
<Route path='/contact' component={Contact} />
<Footer />
</div>
</Router>
);
}
}
testProducts.js
render() {
return (
<div>
<section>
<h1 className='text-center'>Products</h1>
<div className='container'>
<div className='row'>
{this.state.products.map(product => {
return (
<div className="col-md-4 col-md-offset-2">
<img className='product' src={product.imagePath} />
<a href="#" id='nutritional-facts' className="btn btn-lg" data-toggle='modal' data-target='#allPurposeNutrional'>Nutritional Facts</a>
<div className="modal fade" id="allPurposeNutrional" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 className="modal-title" id="myModalLabel">Nutrional Facts</h4>
</div>
<div className="modal-body text-center">
<img src={product.nutritionImagePath} alt="All Purpose Nutritional Facts" />
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<h5>All Natural All Purpose</h5>
<button onClick={this.props.addToCart(product._id)} >Add To Cart</button>
</div>
)
})}
</div>
</div>
</section>
</div>
);
}
}
はI Iとしてナンセンスの多くのようなコードに折り畳まれた
app.jsを動作させることはできません可能性があります。 TestProductsファイルにメソッドがあると、コードは正常に動作するので、正常に動作します。 App.jsファイルにコードを書き込むと、コンソールが表示されません。ネットワークリクエストが表示されず、呼び出されません。
すべてのヘルプをありがとうございました!
コンポーネントが大きすぎる場合は、2〜3個の小さなコンポーネントで構成する必要があります。コンテナコンポーネントも使用していません。あなたのビューとあなたのルートの間のステップとして。あなたがコンポーネントの束の上に共有したい機能を追加する限り、私は再びreduxを働こうとすることをお勧めします。そのすばらしい図書館は、それほど難しいことではありません。卵頭ioに関するチュートリアルがたくさんあります。チェックアウトしてください。 –
チップのおかげで。私は最初にreduxを使い始めました。他のいくつかのプロジェクトでそれを使用していましたが、私も同じように好きです。データを渡すのが100万回になると思いますが、私はサーバ上でセッションを使用しています。そして、私はまだ比較的新しいものです。再びヒントのおかげで – boomer1204